Reputation: 803
I'm writing Unit tests for each seperate module I have. One of these module is a command queue (to ease the asynchronous loading of the script):
in html head:
<script>
var advert = advert || {};
advert.cmd = advert.cmd || [];
</script>
cmd.js:
let cmd = (function(cmd) {
const queue = cmd;
function _init() {
while(queue.length > 0) {
_next();
}
}
function _next() {
queue.shift().call();
}
function _push(fn) {
console.log('pushing', fn);
if (!fn instanceof Function) {
throw Error('core.cmd - argument not of type Function');
}
queue.push(fn);
_next();
}
return {
'init': _init,
'queue': queue,
'push': _push
}
}(window.advert.cmd || []));
export default cmd;
As for my Unit test I have the following:
import cmd from './../src/utils/cmd';
beforeAll(() => {
global.advert = {};
global.advert.cmd = [];
});
describe('Given we use a queue', () => {
let functionResult;
beforeEach(() => {
functionResult = 0;
});
describe('When the queue is initialized', () => {
test('It should execute the already contained functions ', () => {
global.advert.cmd = [
function(){functionResult++},
function(){functionResult++}
];
global.advert.cmd = cmd;
global.advert.cmd.init();
expect(functionResult).toBe(2);
});
});
});
When running the test I get this error message:
TypeError: Cannot read property 'cmd' of undefined
This error points towards the iife argument in the cmd.js file: }(window.advert.cmd || []));
I first thought it had to do with the window object that needs to be renamed to global (within the tests) but even that doesn't change the error message. Any ideas?
Thanks
Upvotes: 1
Views: 1522
Reputation: 2756
Create a file like prepare-environement.js
global.advert = {};
global.advert.cmd = [];
and import it before cmd.js
import './prepare-environement'
import cmd from './../src/utils/cmd';
Upvotes: 2