【问题标题】:How to mock a date object using Jest?如何使用 Jest 模拟日期对象?
【发布时间】:2021-01-16 13:06:42
【问题描述】:

我正在处理一个测试用例,我需要比较期望块中的日期字段(creation_timelast_attempt_time)。有时它会由于日期更改中的毫秒值而失败。所以我需要模拟一个日期对象,它应该返回指定的日期,并且它应该用于所有测试用例模块,只要在项目的测试用例中使用 Date 对象。

// sample.test.ts

it('should return an reset object', () => {

    // Preparing
    const updatedChangeRequest: any = {
        creation_time: new Date(),
        attempts: 0,
        last_attempt_time: new Date()
    };

    // Executing
    const result = ClassName.methodName();

    // Verifying
    expect(result).toEqual(updatedChangeRequest);
});

【问题讨论】:

标签: node.js unit-testing date mocking jestjs


【解决方案1】:

这里有几个选项。例如,您可以重新分配整个 Date 对象并将其替换为模拟实现或覆盖单个方法(然后在运行测试用例后恢复它们)。但是已经有 a module called mockdate in npm 了。

使用模拟日期,您可以:

const MockDate = require('mockdate');

it('should return an reset object', () => {       
    MockDate.set(Date.now()); // sets now to Date.now()

    // Preparing
    const updatedChangeRequest: any = {
        creation_time: new Date(),
        attempts: 0,
        last_attempt_time: new Date()
    };
    // Executing
    const result = ClassName.methodName();
    // Verifying
    expect(result).toEqual(updatedChangeRequest);

    MockDate.reset();
});

要在所有测试文件中模拟 Date,您可以在您的 jest 配置文件中设置 setupFilesAfterEnv

// jest.config.js
{
  // ...
  setupFilesAfterEnv: [
    "./mockdate.js"
  ]
}

// mockdate.js
const MockDate = require('mockdate');

beforeAll(() => {
  MockDate.set(Date.now());
});

afterAll(() => {
  MockDate.reset();
});

要确认它是否有效,您可以运行以下测试:

// mockdate.test.js

test('It Should always return the same value for Date.now()', async () => {
  const before = Date.now();
  await new Promise((resolve, reject) => setTimeout(resolve, 1000));
  const after = Date.now();
  expect(before).toEqual(after);
});

【讨论】:

  • 您好,谢谢您的建议。但我有 15 个测试用例文件。如果我遵循这一点,我必须对所有模块中的所有测试套装使用 beforeAll 和 afterAll。有没有办法把它作为一个像手动模拟一样的通用文件?并避免在每个模块上声明。
  • 效果很好,谢谢!有没有办法在不使用诸如 mockdate 和 momentJS 之类的 3rd 方包的情况下实现这一点?
  • Mockdate 的存储库托管在 GitHub 上,主脚本包含大约 80 行代码。您可以阅读代码并借用您需要的部分。
  • 嘿,我尝试了这段代码,但最终出现错误说明 TypeError: Date.now is not a function ``` const mockDate: any = new Date(1466424490000 ) const spydate= jest.spyOn(global, 'Date').mockImplementation(() => mockDate) ```
猜你喜欢
  • 1970-01-01
  • 2019-10-13
  • 2017-12-20
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2019-12-31
相关资源
最近更新 更多