mardi 1 mars 2016

Is it possible to set the value of `this` when using Sinon.JS and Rewire?

Background

If I have the following module:

this_module: {

    foo: {};

    set_this_foo: function () {

        this.foo.boo = 'something';
        return this.foo;
    }
}

and use Rewire to import the private function and then unit test this function using Sinon.js:

var set_this_foo = app.__get__('this_module.set_this_foo');
var spy = sinon.spy(set_this_foo);

spy();

expect(spy).to.have.returned({boo: 'something'});

I get the error message:

TypeError: Cannot set property 'boo' of undefined

because this ends up having the value of the global object. I can fix this issue by defining a global variable named foo before running the test, but would prefer not to pollute the global namespace.

Question

Is there an (elegant) way to define the value of this in relation to spy()?

Aucun commentaire:

Enregistrer un commentaire