Search code examples
javascriptsinonchaisinon-chai

Sinon: Test the order of function call and var change


When we have

// arrange
var testVar = 0;
var testFunction = sandbox.stub();

// act
TestClass.TestMethod(); // it changes testVar and calls testFunction

Is there a way to test if testVar is changed before testFunction is called?

Edit: looks like there isn't. But! You can do something similar if the variable is an object property. Check my own answer below.


Solution

  • Ok, so looks like it can't really be done.

    However, I did find a way to test with object properties. Example pseudo code:

    before(function() {
        var functionCallOrder = [];
    
        document.body.classList.add = function() {
            functionCallOrder.push('added class');
        };
    
        Object.defineProperty(document.body, 'scrollTop', {
            set: function() {
                functionCallOrder.push('changed viewport location');
            }
        });
    
        it('should set a class before changing the viewport location'), function() {
                // act
                MyModule.methodThatDoesWhatTheDescriptionSays();
    
                // assert
                expect(functionCallOrder).to.deep.equal([
                    'added class',
                    'changed viewport location'
                ]);
        });
    });