The following code shows a pattern I've been discussing with other developers. The tests were developed to allow a developer to see that the functions inside code-under-test are firing in a particular order.
The code can be found HERE on GitHub.
Code Under Test
Here is the code that will be under test. Note the inOrder
and outOfOrder
functions. The expectation is that these child functions, one
, two
, three
, four
, and five
, would execute in this order ...
const testableCode = {
one: () => {},
two: () => {},
three: () => {},
four: () => {},
five: () => {},
inOrder: () => {
testableCode.one();
testableCode.two();
testableCode.three();
testableCode.four();
testableCode.five();
},
outOfOrder: () => {
testableCode.one();
testableCode.two();
testableCode.three();
testableCode.five();
testableCode.four();
}
};
What we are looking to do is test that the functions to execute the child functions in a particular order.
Testing
Here are the tests ...
describe('code: order of operations', function() {
it('tests specific order', function() {
// WHITE BOX TESTED
let order = '';
spyOn(testableCode, 'one').and.callFake(function() { order += '1,'; });
spyOn(testableCode, 'two').and.callFake(function() { order += '2,'; });
spyOn(testableCode, 'three').and.callFake(function() { order += '3,'; });
spyOn(testableCode, 'four').and.callFake(function() { order += '4,'; });
spyOn(testableCode, 'five').and.callFake(function() { order += '5'; });
testableCode.inOrder();
expect(order).toBe('1,2,3,4,5');
});
it('tests out of order', function() {
// WHITE BOX TESTED
let order = '';
spyOn(testableCode, 'one').and.callFake(function() { order += '1,'; });
spyOn(testableCode, 'two').and.callFake(function() { order += '2,'; });
spyOn(testableCode, 'three').and.callFake(function() { order += '3,'; });
spyOn(testableCode, 'four').and.callFake(function() { order += '4,'; });
spyOn(testableCode, 'five').and.callFake(function() { order += '5'; });
testableCode.outOfOrder();
expect(order).not.toBe('1,2,3,4,5');
});
In each of the tests a string is used to track the actual calling order. The first test is testing proper order, the second test verifies that the test will fail if they are not in order.
I chose a string to track the order of execution strictly for its simplicity.
This is a simply WHITE BOX testing pattern that can be used as functionality is abstracted out to maintain consistency.