首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >输出方法的函数存根

输出方法的函数存根
EN

Stack Overflow用户
提问于 2020-03-09 06:02:43
回答 2查看 185关注 0票数 0

我正在使用一个名为adm-zip的模块,我就是这样将它添加到我的文件中的。

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

发布于 2020-09-18 22:57:51

您展示的代码段仅包含与adm-zip的交互。因此,您希望在单元测试中找到什么样的bug?

在这里,人们唯一希望看到的bug是adm-zip的使用中的错误:调用错误的构造函数,传递错误的参数等等。然而,在创建模拟时,您永远不会发现这些bug:因为您自己实现了模拟,所以您实现它们的基础是编写代码时所理解的相同(错误)。

因此,要找到这样的bug,您必须与真正的adm集成测试您的代码,因为只有这样,您才能找到您对adm-zip模块的理解中的缺陷。

结论:跳过单元测试,直接进行集成测试.

票数 1
EN

Stack Overflow用户

发布于 2020-03-09 09:36:45

您需要使用丙氧奎尔模块对adm-zip模块进行存根。

例如。

index.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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%覆盖范围的单元测试结果:

代码语言:javascript
复制
  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 |                   
----------|---------|----------|---------|---------|-------------------
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60595390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档