typescript - 开玩笑的模拟时刻()
问题描述
我尝试模拟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 未定义
如果我删除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
推荐阅读
- javascript - IN 和 NOT IN 子查询结果不一致
- laravel - 如何在 laravel 中使用图表包?
- visual-studio-code - 如何在 VSCode/flutter 中升级包?
- php - PHP检查字符串是否包含数组中的单词
- python - Django ImageField 为空
- flask - 随机时间没有 user_loader 异常(重置时消失)
- c# - 实现自定义路由属性,如 HttpGet
- datastax - DSE 图中的多面体
- sql - 长选需要 55 秒才能显示结果,更好的咨询方式?
- redux - 如何让 takeLatest 考虑 url、参数和方法?