我试图在使用简单配置对象的过程中添加测试。假设我有:
config.ts
export default {
foo: "bar",
};app.ts
import config from "./config";
export default () => {
return config.foo;
};app.test.ts
import App from "./app";
import config from "./config";
describe("App", () => {
beforeEach(() => {
jest.mock("./config", () => ({ default: { foo: "mock foo" } }));
});
it("returns a mocked value of config.foo", () => {
config.foo = "baz";
expect(App()).toBe("baz");
});
it("returns the default value of config.foo", () => {
expect(App()).toBe("bar");
});
});第二个测试失败是因为在第一个测试中修改了真正的配置,但我希望它失败,因为beforeEach中的模拟已经将值设置为“模拟foo”。我认为这与配置导出不是一个函数有关,所以我不能做类似于jest.spyOn...的事情。然而,如果有一种方法来模拟一个对象,它将在我正在处理的项目中为我节省一个大型重构!
发布于 2020-11-30 03:49:41
您可以使用jest.doMock(moduleName,工厂,选项)来模拟每个测试用例的./config模块。
例如。
config.ts
export default {
foo: 'bar',
};app.ts
import config from './config';
export default () => {
return config.foo;
};app.test.ts
describe('App', () => {
beforeEach(() => {
jest.resetModules();
});
it('returns a mocked value of config.foo', () => {
jest.doMock('./config', () => ({ foo: 'baz' }));
const App = require('./app').default;
expect(App()).toBe('baz');
});
it('returns the default value of config.foo', () => {
jest.doMock('./config', () => ({ foo: 'bar' }));
const App = require('./app').default;
expect(App()).toBe('bar');
});
});单元测试结果:
PASS src/stackoverflow/65049305/app.test.ts (12s)
App
✓ returns a mocked value of config.foo (8ms)
✓ returns the default value of config.foo (1ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 13.288shttps://stackoverflow.com/questions/65049305
复制相似问题