带有Jest的CommonJS模块的多个手动安装 [英] Multiple Manual Mocks of CommonJS Modules with Jest
问题描述
我使用 mocks 文件夹查看了Jest的模拟文档,但是我希望能够在一个测试中模拟一个模块并在另一个测试中模拟另一个模块.
I saw the documentation for Jest's mocks using the mocks folder, but I want to be able to mock a module with one mock in one test and mock that same module with another mock in another test.
例如,使用rewire和茉莉花,您可以执行以下操作:
For example, with rewire and jasmine, you could do something like this:
//module2.js
module.exports = {
callFoo: function () {
require('moduleToMock').foo();
}
};
//module2Test.js
describe("test1", function () {
var mock;
beforeEach(function () {
var rewire = require('rewire');
mock = jasmine.createSpyObj('mock', ['foo']);
});
it("should be mocked with type1", function () {
mock.foo.and.returnValue("type1");
rewire('moduleToMock', mock);
var moduleUsingMockModule = require('module2');
expect(moduleUsingMockModule.callFoo()).toEqual("type1");
});
});
describe("test2", function () {
it("should be mocked with type2", function () {
mock.foo.and.returnValue("type2");
rewire('moduleToMock', mock);
var moduleUsingMockModule = require('module2');
expect(moduleUsingMockModule.callFoo()).toEqual("type2");
});
});
这可能与Jest有关吗?区别在于,我在测试中定义了模拟,而不是在用于所有测试的某些外部文件夹中定义.
Is this possible to do with Jest? The difference is I define the mock within the test, not in some external folder that is used for all tests.
推荐答案
是的,您的模拟将如下所示:
Yes, your mock will look like this:
module.exports = {
foo: jest.genMockFunction();
}
然后,您将能够在测试用例中配置自定义行为:
Then you will be able to configure a custom behaviour in your test cases:
var moduleToMock = require('moduleToMock');
describe('...', function() {
it('... 1', function() {
moduleToMock.foo.mockReturnValue('type1')
expect(moduleToMock.foo).toBeCalled();
expect(moduleUsingMockModule.callFoo()).toEqual("type1");
});
it('... 2', function() {
moduleToMock.foo.mockReturnValue('type2')
expect(moduleToMock.foo).toBeCalled();
expect(moduleUsingMockModule.callFoo()).toEqual("type2");
});
});
这篇关于带有Jest的CommonJS模块的多个手动安装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!