Apr 21, 2023
Sinon stubs have a callsFake()
perform that tells Sinon what perform to name as an alternative of the stubbed perform.
For instance, you’ll be able to substitute the axios.get()
perform with a faux perform as follows.
const axios = require('axios');
const assert = require('assert');
const stub = sinon.stub(axios, 'get').
callsFake(() => Promise.resolve({ standing: 200 }));
const take a look at = await axios.get('https://httpbin.org/get');
take a look at.standing;
take a look at.knowledge;
The callsFake()
perform is useful for testing, as a result of you’ll be able to configure the habits of any perform name to deal with hard-to-test code paths.
For Async Features
To stub async features, we sometimes advocate making your faux perform return a promise utilizing Promise.resolve()
.
Ensuring your faux perform returns a promise is very necessary if you’re utilizing promise chaining, as a result of in any other case you will not have the ability to name then()
.
const stub = sinon.stub(axios, 'get').
callsFake(() => Promise.resolve({ standing: 200 }));
You may as well move an async perform to callsFake()
.
Nevertheless, that may be indicative of a code odor, as a result of faux features sometimes ought to not do something in addition to returning a pre-defined worth.
Multi-line faux features are sometimes pointless.
Nevertheless, it’s possible you’ll use the next syntax as an alternative of Promise.resolve()
as a result of the next is extra concise.
const stub = sinon.stub(axios, 'get').
callsFake(async () => ({ standing: 200 }));
For Errors
You may as well make your faux features throw errors for testing error instances.
For instance, you can also make a stub return a rejected promise as follows.
const axios = require('axios');
const assert = require('assert');
const stub = sinon.stub(axios, 'get').
callsFake(() => Promise.reject(new Error('Oops!')));
attempt {
await axios.get('https://httpbin.org/get');
} catch (err) {
err.message;
}
You may as well throw an error from the faux perform physique.
Simply ensure you’re constant about async features vs sync features: for those who’re stubbing an async perform, ensure you both return a promise or use an async faux perform!
sinon.stub(axios, 'get').
callsFake(() => Promise.reject(new Error('Oops!')));
sinon.stub(axios, 'get').
callsFake(async () => { throw new Error('Oops!'); });
sinon.stub(axios, 'get').
callsFake(() => { throw new Error('Oops!'); });