【问题标题】:Mock moment() in jest开玩笑的模拟时刻()
【发布时间】:2019-10-18 21:11:21
【问题描述】:

我尝试模拟 moment() 以避免快照测试基于一天中的时间失败.. 我的<Header /> 有一个功能,它使用moment() 来显示不同的问候(Hello早安晚安等)

我的测试功能:

jest.mock('moment', () => moment().month(11).date(24)); //Should give "happy xmas"
it("Match snapshop", () => {
    act(() => {
        container = shallow(<Header />);
    });
    expect(container).toMatchSnapshot();
});

但是当我运行测试时,我得到:

ReferenceError: moment_1 未定义

如果我删除 jest.mock(....) 测试运行,但结果取决于一天中的时间..

【问题讨论】:

  • 我相信你最好不要模拟moment,因为你必须在模拟中重新实现你的代码使用的所有方法(以一致的方式)。有很多事情要做。相反,您可以模拟全局 Date/Date.now 以返回陈旧值。
  • 使用@skyboyer 的解决方案解决:jest.spyOn(global.Date, "now").mockImplementationOnce(() => new Date("2019-12-24T11:01:58.135Z" ).valueOf() );

标签: typescript testing jestjs


【解决方案1】:

正如@skyboyer 所说。您应该模拟 JS 原生 Date 而不是 moment 模块。这是一个完整的演示:

index.tsx:

import React from 'react';
import moment from 'moment';

export class Header extends React.Component {
  public render() {
    const date = moment()
      .month(11)
      .date(24);

    return <div>{date.toString()}</div>;
  }
}

index.spec.tsx:

import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { Header } from './';

describe('Header', () => {
  it('match snapshot', () => {
    jest.spyOn(Date, 'now').mockReturnValueOnce(new Date('2019/11/24').getTime());
    const wrapper: ShallowWrapper = shallow(<Header></Header>);
    expect(wrapper.text()).toBe('Tue Dec 24 2019 00:00:00 GMT+0800');
    expect(wrapper).toMatchSnapshot();
  });
});

index.spec.tsx.snap:

// Jest Snapshot v1

exports[`Header match snapshot 1`] = `
<div>
  Tue Dec 24 2019 00:00:00 GMT+0800
</div>
`;

100% 覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/56425230/index.spec.tsx
  Header
    ✓ match snapshot (14ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        3.592s, estimated 7s

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多