如何使用 sinon/mocha 模拟 npm 模块 [英] How to mock npm module with sinon/mocha
本文介绍了如何使用 sinon/mocha 模拟 npm 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测试一个调用模块 cors
的函数.我想测试 cors
是否会被调用.为此,我必须存根/模拟它.
I'm trying to test a function that calls the module cors
. I want to test that cors
would be called. For that, I'd have to stub/mock it.
这是函数cors.js
Here is the function cors.js
const cors = require("cors");
const setCors = () => cors({origin: 'http//localhost:3000'});
module.exports = { setCors }
我测试此类功能的想法类似于
My idea of testing such function would be something like
cors.test.js
cors.test.js
describe("setCors", () => {
it("should call cors", () => {
sinon.stub(cors)
setCors();
expect(cors).to.have.been.calledOnce;
});
});
知道如何存根 npm 模块吗?
Any idea how to stub npm module?
推荐答案
您可以使用 mock-require
或 proxyquire
mock-require
const mock = require('mock-require')
const sinon = require('sinon')
describe("setCors", () => {
it("should call cors", () => {
const corsSpy = sinon.spy();
mock('cors', corsSpy);
// Here you might want to reRequire setCors since the dependancy cors is cached by require
// setCors = mock.reRequire('./setCors');
setCors();
expect(corsSpy).to.have.been.calledOnce;
// corsSpy.callCount should be 1 here
// Remove the mock
mock.stop('cors');
});
});
如果您愿意,您可以在每个测试之间使用 corsSpy.reset()
在描述和重置间谍之上定义模拟,而不是为每个测试模拟和停止模拟.
If you want you can define the mock on top of describe and reset the spy using corsSpy.reset()
between each tests rather than mocking and stopping the mock for each tests.
这篇关于如何使用 sinon/mocha 模拟 npm 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文