I have written a small piece of code to understand the sinon functionality.
Below is the piece of code to check:
toBeTested.js
:
const getAuthenticationInfo = orgId => {
return 'TEST';
};
const getAuthToken = orgId => {
var lmsInfo = getAuthenticationInfo(orgId);
return lmsInfo;
};
module.exports = {
getAuthenticationInfo,
getAuthToken
};
api-test.js
:
const sinon = require('sinon');
const toBeTested = require('./toBeTested');
sinon.stub(toBeTested, 'getAuthenticationInfo').returns('mocked-response');
console.log(toBeTested.getAuthInfo());
I am expecting console.log
output as mocked-response
. But it is giving response as TEST
.
Here is the unit test solution:
index.js
:
const getAuthenticationInfo = orgId => {
return 'TEST';
};
const getAuthToken = orgId => {
var lmsInfo = exports.getAuthenticationInfo(orgId);
return lmsInfo;
};
exports.getAuthenticationInfo = getAuthenticationInfo;
exports.getAuthToken = getAuthToken;
index.spec.js
:
const mod = require('./');
const sinon = require('sinon');
const { expect } = require('chai');
describe('53605161', () => {
it('should stub getAuthenticationInfo correctly', () => {
const stub = sinon.stub(mod, 'getAuthenticationInfo').returns('mocked-response');
const actual = mod.getAuthToken(1);
expect(actual).to.be.equal('mocked-response');
expect(stub.calledWith(1)).to.be.true;
stub.restore();
});
it('getAuthenticationInfo', () => {
const actual = mod.getAuthenticationInfo();
expect(actual).to.be.equal('TEST');
});
});
Unit test result with 100% coverage report:
53605161
✓ should stub getAuthenticationInfo correctly
✓ getAuthenticationInfo
2 passing (7ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
index.spec.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/53605161
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.