我尝试模拟<execution>
<id>jaxwsgenInterface</id>
<phase>generate-sources</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>java</executable>
<longClasspath>false</longClasspath>
<arguments>
<arguments>-classpath</arguments>
<classpath/>
<argument>-Djavax.xml.parsers.DocumentBuilderFactory=oracle.xml.jaxp.JXDocumentBuilderFactory</argument>
<argument>-Djavax.xml.parsers.SAXParserFactory=oracle.xml.jaxp.JXSAXParserFactory</argument>
<argument>-Djavax.xml.transform.TransformerFactory=oracle.xml.jaxp.JXSAXTransformerFactory</argument>
<argument>-Djavax.xml.xpath.XPathFactory:http://java.sun.com/jaxp/xpath/dom=oracle.xml.xpath.JXPathFactory</argument>
<argument>oracle.j2ee.ws.tools.wsa.Main</argument>
<argument>jaxwsgenInterface</argument>
<argument>wsdl</argument>
<argument>schema/Service.wsdl</argument>
<argument>wsdlLocation</argument>
<argument>WEB-INF/wsdl/Service.wsdl</argument>
<argument>output</argument>
<argument>target/gensrc</argument>
<argument>debug</argument>
<argument>true</argument>
</arguments>
</configuration>
</execution>
以避免快照测试根据一天中的时间失败。
我的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
,则测试会运行,但结果取决于一天中的时间。
答案 0 :(得分:0)
正如@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