Bhu*_*wan 2 unit-testing mocha.js node.js sinon chai
我已经为下面的函数编写了测试用例(我省略了很多不必要的代码,只提供了必要的东西,但如果你需要任何其他信息,请告诉我)。
static getLibs() {
return new Promise((resolve, reject) => {
const instance = new LibClass();
instance.loadLibs().then((libs) => {
if (!libs) {
return LibUtils.createLib();
} else {
return Promise.resolve([]);
}
}).then(resolve).catch((err) => {
//log stuff here
})
})
}
export default class LibClass {
//constructor
//method
createLib() {
return new Promise(() => {
//some stuff
})
}
}Run Code Online (Sandbox Code Playgroud)
describe('Library', () => {
it('should get libs', () => {
let obj = new LibClass();
let mstub = sinon.stub(obj, 'loadLibs').returns(Promise.resolve('success'));
return LibWrapper.getLibs().then((res) => {
expect(mstub.called);
}, (err) => {
//log stuff
})
}).catch((exp) => {
//log stuff
})
})Run Code Online (Sandbox Code Playgroud)
但是每当我在测试用例之上运行时,都不会调用 stub 方法。谁能建议我在这里做错了什么?
您可以在LibClass原型上创建存根,而不是在实例上创建它。如果你这样做,那么你需要在测试后恢复它,这样它就不会污染你的其他测试:
describe('Library', () => {
let mstub;
beforeEach(() => {
mstub = sinon.stub(Libclass.prototype, 'loadLibs').returns(Promise.resolve('success'));
});
afterEach(() => {
mstub.restore()
});
it('should get libs', () => {
let obj = new LibClass();
return LibWrapper.getLibs().then((res) => {
expect(mstub.called);
}, (err) => {
//log stuff
})
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3850 次 |
| 最近记录: |