My codes:
it('should', sinon.test(function() {
console.log(this); // what `this` refer here?
...
}));
In the above code, what this
refer in the sinon.test()
function?
I tried to log it, but got the error:
TypeError: Converting circular structure to JSON
Sinon version: 1.17.6
Any comments welcomed. Thanks.
UPDATE
after reading the below answer, I am still confused. Why the following two pieces of codes work when this.myOnject.log
was stubbed only once?
it('should', sinon.test(function() {
const stubLog = this.stub(this.myObject.log, 'warn');
// ...
this.myObject.process();
// expect codes...
}));
it('should', sinon.test(function() {
const stubLog = sinon.stub(this.myObject.log, 'warn');
// ...
this.myObject.process();
// expect codes...
}));
UPDATE
If downvoted, please leave some comments to let me know why you downvoted. I am very confused by the question I posted. But I am more confused why so many people downvoted, but did not leave any useful comments.
sinon.test
creates a new Sinon sandbox for your test and augments the normal this
object that Mocha passes to your test with Sinon-specific methods like spy
, stub
, etc. that call the corresponding methods on the sandbox that is automatically created. The fact that it augments the object allows you to still use all the stock Mocha methods that Mocha normally provides on this
, and allows you to set values on arbitrary fields. The restore
method of the sandbox is automatically called when the test ends. It is a convenient way to provide isolation between tests so that modifications to common objects that one test performs through Sinon don't affect other tests.
Here's an example:
const sinon = require("sinon");
before(function () {
// We set "moo".
this.moo = "I'm a cow.";
});
it("test", sinon.test(function () {
// We can access "stock" Mocha functions.
this.timeout(0);
// However, this is augmented with sinon functions.
const spy = this.spy();
spy();
// We can access "moo";
console.log("value of moo", this.moo);
}));
This produces:
value of moo I'm a cow.
✓ test
1 passing (34ms)
The code above assumes Sinon 1.x. In Sinon 2.x and over sinon.test
is no longer bundled with Sinon but is its own separate package.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments