[英]Stub function test with sinon/nodejs
I have a problem with sketching a function with sinon.我在用 sinon 绘制函数时遇到问题。
The problem is to return a result or to throw an error in a function of another function.问题是返回结果或在另一个函数的函数中抛出错误。
As below:如下:
service.js服务.js
async function functionA() {
var resultB = functionB();
}
function functionB() {
return "FuncB";
}
module.exports = {
functionA,
functionB
}
service.test.js服务.test.js
const { assert } = require("chai");
const sinon = require("sinon");
const service = require("./service");
it('Should return error.', async function() {
var stub = sinon.stub(service, 'functionB').returns('functionC');
var functionTotest = service.functionA();
assert(stub.calledOn(functionTotest));
});
The function is not simulating an error or the return that I set.该函数没有模拟我设置的错误或返回。
The stub does not work and enters the function.存根不工作,进入函数。
Here is the unit test solution:这是单元测试解决方案:
service.js
: service.js
:
async function functionA() {
var resultB = exports.functionB();
return resultB;
}
function functionB() {
return 'FuncB';
}
exports.functionA = functionA;
exports.functionB = functionB;
service.test.js
: service.test.js
:
const { assert, expect } = require('chai');
const sinon = require('sinon');
const service = require('./service');
it('Should return error.', async function() {
var stub = sinon.stub(service, 'functionB').returns('functionC');
var actual = await service.functionA();
expect(actual).to.be.equal('functionC');
expect(stub.calledOnce).to.be.true;
});
Unit test result with coverage report:带有覆盖率报告的单元测试结果:
✓ Should return error.
1 passing (9ms)
-----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files | 92.31 | 100 | 66.67 | 92.31 | |
service.js | 80 | 100 | 50 | 80 | 7 |
service.test.js | 100 | 100 | 100 | 100 | |
-----------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56759906源代码: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56759906
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.