Unit Testing - sgml/signature GitHub Wiki
Testing in Eiffel is primarily based on the Design by Contract (DbC) methodology, which integrates testing directly into the software development process. Here's how it works and what makes it unique:
- Preconditions: These define the conditions that must be true before a method is executed. If the precondition is violated, an exception is raised.
- Postconditions: These define the conditions that must be true after a method has executed. If the postcondition is violated, an exception is raised.
- Class Invariants: These define conditions that must always be true for all instances of a class. They are checked at the beginning and end of every method call to ensure consistency.
- Automatic Testing: EiffelStudio, the integrated development environment for Eiffel, includes tools like AutoTest that automatically generate tests based on the contracts defined in the code.
- Continuous Contract Checking: Eiffel's runtime system continuously checks contracts (preconditions, postconditions, and invariants) during execution, ensuring that the software adheres to its specifications at all times.
- Regression Testing: The suite of tests can be run at any time to ensure that changes or additions to the code do not break existing functionality.
import unittest class TestImport(unittest.TestCase): def test_import(self): with self.assertRaises(ImportError): import non_existent_module if __name__ == '__main__': unittest.main()
The way unit testing works you have to take the entire engine apart and put it back multiple time until you find where the weird noise is coming from.
The way integration testing works you have to swap old parts for new parts and see if the engine sounds the same with either one.
The way end-to-end testing you need to turn the key and drive around the block.
Avoid adding tests which may return false positives or false negatives in the future. To do this, prefer tests based on numbers rather than complex boolean logic.
Mockgen: var mock = 'window.name'.replace('.', '":{"').replace(/^/,'{"').replace(/$/,'":""}}')
Stubgen: function foo(value){ return /.=.=>.{/.exec(value) ? /.*=>.{/.exec(value).toString() : false} function bar(value){ return value } function baz(value){ return String("SearchViewModel." + value).trim().replace(/[\s=>{}]/g,"")} var arrows = document.querySelector("pre").innerText.split("\n").map(foo).filter(bar) var stubs = arrows.map(baz) window.stubs = stubs;
Installing Jasmine standalone
Download the latest Jasmine release from the Jasmine release page:
Running Jasmine locally
- Run Jasmine in the browser by downloading the zip file, extracting it, the referencing the files as follows:
<script type="text/javascript" src="jasmine/lib/jasmine-2.0.0/jasmine.js"></script> <script type="text/javascript" src="jasmine/lib/jasmine-2.0.0/jasmine-html.js"></script> <script type="text/javascript" src="jasmine/lib/jasmine-2.0.0/boot.js"></script>
Installing Jasmine using npm (Node Package Manager)
-
Set up project directory for Jasmine
Create a folder and run
npm init
this will create an emptypackage.json
file and will ask some questions about your project to fill projectjson
file.Add 2 directories
app
- for the Server andspec
- for tests -
Get Jasmine
From root project directory run
npm install jasmine-node --save
npm install request --save
npm install express --save
this will get you the packages
./node_packages/.bin/jasmine-node spec
will run jasmine binaryAfter this your
package.json
should look similar to thispackage.json file, after which that file should look like this:
{ "name": "Jasmine", "version": "0.0.1", "description": "Jasmine", "main": "index.js", "scripts": { "test": "./node_modules/.bin/jasmine-node spec" }, "author": "Me", "license": "ISC" }
Install with npm
npm install -g jasmine
If being used with karma, install karma-jasmine
npm install --save-dev karma-jasmine
toBeDefined toBeTruthy toBeFalsy toThrow toBe toEqual
ok equal notEqual raises deepEqual strictEqual
to test if something is not undefined to test if two primitive values are equal to test if two primitive values are not equal to test if a callback throws an exception to test if two objects are the same to test if two primitive values are equal and the same type
module('foo', bar);
function bar() { /* Move to before or setup step / var glob = ""; var app = init(public_method); app.method = function(){ / move to spy */ console.log(app.public_method());
return app.public_method(); }; /* move to QUnit or Jasmine assert syntax equivalent */ console.assert(app.method, true, "foo"); /* Move to after or teardown step */ app.on("destroy", function(){ var glob = app = undefined; }) }
describe('name',cb)function pre() { myglobalvar = 'https://us.etrade.com'; myglobalfn = Date(); myglobalnamespace = mvstar;
mvstar.init();
spyOn(mvstar, "public method"); }function post() { var myglobalvar = myglobalnamespace = myglobalfn = app = undefined; }
function cb() { beforeEach(pre); it('behavior', function() { app.method(); expect(mvstar.init).toBeDefined(); expect(mvstar.public_method).toHaveBeenCalled(); } afterEach(post); }
module('name',cb)function pre() { var glob = "" var app = init(); }
function post() { var glob = app = undefined; }
function cb() { setup(pre); test('behavior', function() { var foo = app.method(); equal(foo, true); } teardown(post); }
myAppDev = angular.module('myAppDev', ['ngMockE2E']); test = angular.injector(['myAppDev']).get('$test'); $httpBackend = angular.injector(['ngMock']).get('$httpBackend');
myAppDev = angular.module('myAppDev'); test = myAppDev.constant('test', ['$http',function($http){}]);
module('trading'); module('et.shared.neoServices'); inject(snapshotServiceTest);function snapshotServiceTest(snapshotService) { var result = snapshotService;
expect(result).toBeDefined(); expect(result.chartQuotes).toBeDefined(); expect(result.chartURL).toBeDefined(); expect(result.indexQuote).toBeDefined(); expect(result.symbolQuote).toBeDefined(); }
'use strict';function snapshotService($q, $http, neoresource, $filter, chartFilter) { var api = { chartQuotes: chartQuotes, indexQuote: indexQuote, symbolQuote: symbolQuote, chartURL: chartURL }; return api; }
angular.module('trading', ['et.shared.neoServices']) /* app.js */ angular.module('trading').factory('snapshotService', snapshotService);
/* describe() maps the plain English behavior to the test codeit() defines the user behavior and the implementation
beforeEach() adds dependencies into the global scope before the test
spyOn() acts as an interceptor to override method calls
toHaveBeenCalled() asserts whether the methods have executed
toHaveBeenCalledWith() asserts whether the method signature is correct
afterEach() removes dependencies from the global scope after the test
spyOn also acts as stub to replace host objects angular.module(['ng'], function($provide) { $provide.value('$window', {location: jasmine.createSpy('location') } ) } ) */
describe("when a song is playing, we can toggle between play and pause", function() { beforeEach(function() { player.play(song); }); it("should pause the song", function() { spyOn( player, "pause" ); // define the spy player.togglePlay( song ); expect( player.pause ).toHaveBeenCalled(); expect( player.pause ).toHaveBeenCalledWith( ); }); it("should play the song", function() { spyOn( player, "play" ); // define the spy player.pause(); // just called here to set up our test to play the song next. player.togglePlay( song ); expect( player.play ).toHaveBeenCalled(); expect( player.play ).toHaveBeenCalledWith( song ); });
/* module() groups tests into a namespacetest() namespaces the test and its implementation
setup() adds dependencies into the global scope before the test
teardown() removes dependencies from the global scope after the test */
module("jQuery#enumerate");
test("chainable", 1, function() { var items = $("#qunit-fixture li"); strictEqual(items.enumerate(), items, "should be chaninable"); });
test("no args passed", 3, function() { var items = $("#qunit-fixture li").enumerate(); equal(items.eq(0).text(), "1. foo", "first item should have index 1"); equal(items.eq(1).text(), "2. bar", "second item should have index 2"); equal(items.eq(2).text(), "3. baz", "third item should have index 3"); });
test("0 passed", 3, function() { var items = $("#qunit-fixture li").enumerate(0); equal(items.eq(0).text(), "0. foo", "first item should have index 0"); equal(items.eq(1).text(), "1. bar", "second item should have index 1"); equal(items.eq(2).text(), "2. baz", "third item should have index 2"); });
/* waits(time) stops code execution for a specified intervalruns(function) resumes execution at the end of the callback
waitsFor( function, msg, maxTimeOUt ) calls its function repeatedly until it returns true, so beware
expect() defines the comparison which should be true at the end */
//Simulates an async function by waiting until it has been called 50 times. var globalCounter = 0; var pingCounter = 0 function returnAfterWait( ){ pingCounter++; if ( pingCounter == 50 ){ globalCounter++; return true; }
}
describe('This is an async test', function(){ //this test waits 500 ms before testing the results it('should test async with timer', function(){ var counter = 0; runs( function(){ setTimeout( function(){ counter++; }, 500 ); }) waits( 505 ); runs( function(){ expect(counter).toEqual( 1 ); }) }); /* This test waits to continue until returnAfterWait() returns true */ it('should test async with a return', function(){ var counter = 0; waitsFor( function() { return returnAfterWait(); },'this is the async message', 5000 ); runs( function(){ expect(globalCounter).toEqual( 1 ); }) }); });
/* asyncTest() is a syntatic sugar forr Test( fn{stop()...start()} )start() resumes execution at the end of the callback
expect() defines the number of assertions we should be triggered once start() is called */ asyncTest("async3", function() { expect(1); $.getJSON("resource", function(result) { deepEqual(result, { status: "ok" }); start(); }); });
[http://msdn.microsoft.com/en-us/magazine/gg490346.aspx BDD Primer]
[http://www.slideshare.net/tasanakorn/javascript-testdriven-development-tdd-with-qunit TDD with QUnit]
[http://benalman.com/talks/unit-testing-qunit.html Unit Testing with QUnit]
[https://www.adobe.com/devnet/html5/articles/unit-test-javascript-applications-with-jasmine.html Unit test JavaScript applications with Jasmine ]
[http://www.slideshare.net/larsthorup/advanced-jasmine Advanced Jasmine]
[http://stackoverflow.com/q/21766034/1113772 Jasmine with PhantomJS]
[http://www.devmynd.com/blog/2014-1-ember-js-testing-with-jasmine Ember.js Testing with Jasmine]
[https://gist.github.com/rjackson/6269405 Basic Ember.js Test Setup with QUnit]
[http://josephchapman.com/post/jasmine-mocks-and-spies/ Jasmine Mocks and Spies]
[http://pivotallabs.com/testing-javascript-promises/ Testing JavaScript Promises]
[http://www.slideshare.net/emwendelin/test-your-javascript Test your JavaScript]
[http://msdn.microsoft.com/en-us/library/hh404088.aspx Unit Testing Web Applications]
[https://github.com/larrymyers/jasmine-reporters Jasmine Reporters Plugin with JUnitXMLReporter]
[https://github.com/jquery/qunit-reporter-junit QUnit JUnit Reporter Plugin]
[https://github.com/devongovett/qunit-cli QUnit CLI NodeJS Plugin]
[https://github.com/gregjsmith/ng-demo-stack Ng Demo Stack:Angular + Browserify + QUnit + Sinon and Phantom]
[http://pivotallabs.com/jasmine-2-0-add-ons/ Jasmine 2.0 and Add-Ons]
[https://github.com/jquery/jquery-simulate jQuery Simulate]
-
https://stackoverflow.com/questions/49886244/how-to-test-class-constructor-in-jest
-
https://stackoverflow.com/questions/29975815/react-unit-test-with-jest-in-es6
-
http://www.hackingwithreact.com/read/1/32/how-to-configure-jest-to-test-react-and-es6
-
https://stackoverflow.com/questions/49656706/test-es6-modules-with-jest
-
http://www.kevinfodness.com/using-jest-to-validate-json-data-shape
References
-
https://sites.google.com/site/unclebobconsultingllc/ant-jspc-and-other-horrors https://ant.apache.org/manual/api/org/apache/tools/ant/taskdefs/optional/jsp/JspC.html
-
https://ant.apache.org/manual/api/org/apache/tools/ant/taskdefs/optional/jsp/JspC.html
-
https://stackoverflow.com/questions/2425721/unit-testing-datetime-now
-
https://medium.com/@skidding/testing-react-components-30516bc6a1b3
-
https://dev.to/elaziziyoussouf/tools-you-need-to-use-in-your-react-components-development--13a7
-
https://codeburst.io/revisiting-node-js-testing-part-1-84c33bb4d711
-
https://medium.com/selleo/testing-react-components-best-practices-2f77ac302d12
-
https://github.com/tb/redux/tree/react-testing/examples/todomvc/src/components/__tests__
-
https://medium.com/@eric_lum/cheatsheet-to-jest-testing-in-javascript-c4415b56cacb
-
https://medium.com/@koba04/testing-react-components-with-react-test-renderer-b4df590d0320
-
https://www.perl.com/article/167/2015/4/15/Unit-test-your-code-on-an-in-memory-database/
-
https://yourbasic.org/algorithms/induction-recursive-functions/
-
https://8thlight.com/blog/cory-foy/2013/01/01/testing-recursion.html
-
https://medium.com/@boriscoder/the-hidden-power-of-jest-matchers-f3d86d8101b0
-
https://semaphoreci.com/community/tutorials/how-to-test-react-and-mobx-with-jest
-
https://dzone.com/articles/the-business-case-for-unit-testing-1
-
https://github.com/showell/Game-Of-Life/blob/master/game.coffee
http://www.oracle.com/us/technologies/java/assertions-139853.html