Search code examples
node.jsgruntjsjasminegrunt-contrib-jasmine

Jasmine spy document.execCommand is not called


I write a test like this

describe('execCommand', function () {
    it('should call document.execCommand', function () {
        spyOn(document, 'execCommand').and.callThrough();
        expect(document.execCommand).toHaveBeenCalledWith('foreColor', false, 'red');
        document.execCommand('foreColor', false, 'red');
    });
});

But it fail Expected spy execCommand to have been called with [ 'foreColor', false, 'red' ] but it was never called. and I don't know why?

Please help.

Note: I run it using grunt-contrib-jasmine 0.9.2


Solution

  • Jasmine's expect function is an assertion at that time rather than an assertion that will be run at the end of the it block, switch the order to see it working:

    describe('execCommand', function () {
      it('should call document.execCommand', function () {
        spyOn(document, 'execCommand').and.callThrough();
        document.execCommand('foreColor', false, 'red');
        expect(document.execCommand).toHaveBeenCalledWith('foreColor', false, 'red');
      });
    });
    <link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
    <script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>