typescript - Jest 模拟 moment()

标签 typescript testing jestjs

我尝试模拟 moment()以避免基于一天中的时间快照测试失败.. 我的<Header />有一个使用 moment() 的函数显示不同的问候语(你好早上好晚上好等)

我的测试函数:

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 is not defined

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

最佳答案

正如@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

关于typescript - Jest 模拟 moment(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56425230/

相关文章:

javascript - Jest genMockFromModule 名为 exports

javascript - Aurelia 应用程序 "Hello World"根本不工作

testing - 如何获得 Soap UI 的响应?

testing - 什么限制了 Gradle 构建中的活跃工作人员数量?

reactjs - 在 Jest 中使用模拟无法找到模块 '../request' 错误

typescript - Vuetify Jest 未知自定义元素 <v-*>

typescript - 如何使用 Webpack 和 Angular2 包含外部 css 文件?

javascript - 将 @query 与 LitElement 和 Typescript 结合使用

TypeScript 处理类型数组或单值

python - 如何测试新的 Django 1.10+ 中间件类