gpt4 book ai didi

javascript - Sinon Stub 单元测试

转载 作者:行者123 更新时间:2023-11-30 06:20:13 26 4
gpt4 key购买 nike

我写了一小段代码来理解 sinon 的功能。

下面是要检查的代码片段:

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());

我期待 console.log 输出为 mocked-response。但它给出的响应是 TEST

最佳答案

这是单元测试解决方案:

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');
});
});

具有 100% 覆盖率报告的单元测试结果:

 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 | |
---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/53605161

关于javascript - Sinon Stub 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53605161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com