我是摩卡测试用例的新手。请让我知道如何为此编写测试案例:
控制器功能:
var k, b = 10;
this.myFunction = function() {
k = 'Test failed';
if(b == 10){
k = 'Test Passed';
}
};
测试用例:
it('Should pass the test', function(){
controller.myFunction();
expect(k).to.equal('Test passed');
});
controller.myFunction()
被调用。但是k
的值变得不确定。请帮我解决这个问题!
您应该使用rewire包来set
或get
在模块范围内定义的私有变量。
例如
controller.js
:
var k,
b = 10;
const controller = {
myFunction: function() {
k = 'Test failed';
if (b == 10) {
k = 'Test Passed';
}
},
};
module.exports = controller;
controller.test.js
:
const rewire = require('rewire');
const { expect } = require('chai');
describe('61384893', () => {
it('should pass', () => {
const controller = rewire('./controller');
controller.myFunction();
expect(controller.__get__('k')).to.be.equal('Test Passed');
});
it('should pass too', () => {
const controller = rewire('./controller');
controller.__set__('b', 1);
controller.myFunction();
expect(controller.__get__('k')).to.be.equal('Test failed');
});
});
具有100%覆盖率的单元测试结果:
61384893
✓ should pass (45ms)
✓ should pass too
2 passing (66ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
controller.js | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------
源代码:https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61384893