Following the advice of @skyboyer, it is recommended to mock the JS native Date
object instead of using the moment
module. Below is a complete demonstration:
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>
`;
Upon running unit tests, the results show 100% coverage:
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