【问题标题】:Mocking a config module with Jest用 Jest 模拟一个配置模块
【发布时间】:2020-11-28 11:57:33
【问题描述】:

我正在尝试围绕使用简单配置对象添加测试。假设我有:

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... 的事情。但是,如果有一种方法可以模拟一个对象,它会在我正在处理的项目中为我节省大量的重构!

【问题讨论】:

标签: typescript jestjs mocking


【解决方案1】:

您可以使用jest.doMock(moduleName, factory, options) 模拟每个测试用例的./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.288s

【讨论】:

    猜你喜欢
    • 2019-08-17
    • 2021-02-04
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2019-04-01
    • 2021-12-04
    • 2019-08-15
    相关资源
    最近更新 更多