我正在使用一个名为adm-zip的模块,我就是这样将它添加到我的文件中的。
const AdmZip = require('adm-zip');
let zip = new AdmZip(filePath);
const response = await zip.extractAllTo(outputPath, true);现在我正在编写单元测试用例,并且我试图对AdmZip进行存根,因为正如所示的这里,它导出了一个函数,当使用new调用时,它返回一个具有我想要存根的方法的对象。
我试过执行sinon.stub(AdmZip.prototype, 'extractAllTo').returns('test');,但是它会引发错误,说明extractAllTo属性不存在。
如何存根AdmZip及其方法extractAllTo
发布于 2020-09-18 22:57:51
您展示的代码段仅包含与adm-zip的交互。因此,您希望在单元测试中找到什么样的bug?
在这里,人们唯一希望看到的bug是adm-zip的使用中的错误:调用错误的构造函数,传递错误的参数等等。然而,在创建模拟时,您永远不会发现这些bug:因为您自己实现了模拟,所以您实现它们的基础是编写代码时所理解的相同(错误)。
因此,要找到这样的bug,您必须与真正的adm集成测试您的代码,因为只有这样,您才能找到您对adm-zip模块的理解中的缺陷。
结论:跳过单元测试,直接进行集成测试.
发布于 2020-03-09 09:36:45
您需要使用丙氧奎尔模块对adm-zip模块进行存根。
例如。
index.js
const AdmZip = require('adm-zip');
async function main() {
const filePath = 'some file path';
const outputPath = './dist';
const zip = new AdmZip(filePath);
const response = await zip.extractAllTo(outputPath, true);
}
module.exports = main;index.test.js
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('60595390', () => {
it('should extract all', async () => {
const admZipInstance = {
extractAllTo: sinon.stub(),
};
const admZipStub = sinon.stub().callsFake(() => admZipInstance);
const main = proxyquire('./', {
'adm-zip': admZipStub,
});
await main();
sinon.assert.calledWithExactly(admZipStub, 'some file path');
sinon.assert.calledWithExactly(admZipInstance.extractAllTo, './dist', true);
});
});100%覆盖范围的单元测试结果:
60595390
✓ should extract all (2951ms)
1 passing (3s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------https://stackoverflow.com/questions/60595390
复制相似问题