Javascript 存根导出方法的函数
我正在使用一个名为adm-zip的模块,这就是我如何将它添加到我的文件中Javascript 存根导出方法的函数,javascript,unit-testing,sinon,Javascript,Unit Testing,Sinon,我正在使用一个名为adm-zip的模块,这就是我如何将它添加到我的文件中 const AdmZip = require('adm-zip'); let zip = new AdmZip(filePath); const response = await zip.extractAllTo(outputPath, true); 现在我正在编写单元测试用例,我正在尝试存根AdmZip,因为如图所示,它导出一个函数,当使用new调用时,它返回一个对象,该对象具有我想要存根的方法 我试着做sinon.s
const AdmZip = require('adm-zip');
let zip = new AdmZip(filePath);
const response = await zip.extractAllTo(outputPath, true);
现在我正在编写单元测试用例,我正在尝试存根AdmZip,因为如图所示,它导出一个函数,当使用new调用时,它返回一个对象,该对象具有我想要存根的方法
我试着做sinon.stub(AdmZip.prototype,'extractAllTo')。返回('test')
但它抛出错误,表示extractAllTo
属性不存在
如何存根AdmZip及其方法extractAllTo?您需要使用模块存根adm-zip
模块
例如
index.js
:
const AdmZip=require('adm-zip');
异步函数main(){
const filePath='some file path';
const outputPath='./dist';
const-zip=新的AdmZip(文件路径);
const response=await zip.extractAllTo(outputPath,true);
}
module.exports=main;
index.test.js
:
const sinon=require('sinon');
const proxyquire=require('proxyquire');
描述('60595390',()=>{
它('should extract all',async()=>{
常量admZipInstance={
extractAllTo:sinon.stub(),
};
const admZipStub=sinon.stub().callsFake(()=>admZipInstance);
常量main=proxyquire(“./”{
“adm zip”:admZipStub,
});
等待main();
sinon.assert.calledWithJustice(admZipStub,“某些文件路径”);
sinon.assert.calledWithJustice(admZipInstance.extractAllTo,'./dist',true);
});
});
100%覆盖率的单元测试结果:
60595390
✓ 应提取所有(2951ms)
1次通过(3秒)
----------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
----------|---------|----------|---------|---------|-------------------
所有文件| 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
您显示的代码片段仅包含与adm zip的交互。因此,您希望在单元测试中发现什么样的bug
在这里,人们唯一会想到的错误是使用adm-zip时出现的错误:调用错误的构造函数、传递错误的参数等。然而,在创建模拟时,您永远不会发现这些错误:因为您自己实现模拟,所以在编写代码时基于相同的(错误)理解来实现它们
因此,要找到这样的bug,您必须将代码与真正的adm-zip进行集成测试,因为只有这样,您才能在对adm-zip模块的理解中找到缺陷
结论:跳过这里的单元测试,直接转到集成测试。我遇到错误
找不到模块。/。
我也尝试给它提供控制器的正确路径。我得到了找不到模块'../../../../controllers/test.controller.ts'
@capture\u of_azkaban我有完全相同的问题,你找到了这个问题的解决方案吗?@Shamshiel我将特定于adm的代码移到了一个单独的util文件中,并在那里创建了一个新函数``导出异步函数extractZip(文件,outputPath){const-zip=new-AdmZip(file);wait-zip.extractAllTo(outputPath,true);}````然后就更容易了。失败:``testStub=sinon.stub(chaincodeUtils,'extractZip')。使用Promise(Promise)。拒绝({message:'Error occurrent while unzip'});``成功:testStub.restore();sinon.stub(chaincodeUtils,'extractZip')。callsFake(函数测试(){return';});