尝试为以下功能创建测试用例。不熟悉异步和等待,将Jest和Enzyme用于React Js。 目标:测试合格 并确保该函数被正确调用
async patchPolicy() {
const { user, services } = this.props;
let { data } = this.state;
let body = {
"Policies": [{
"Choices": data.Choices ||''
}]
}
PolicyModels.patchWork({
user,
services,
body,
id: this.state.Policy
})
let contextBody = data.WORK_CONTEXT[0];
let Context_UID = '';
let method = 'POST';
if(contextBody) { //
if(contextBody.Context_UID) { //If has UID, Patch
PolicyModels.patchWorkContext({
user,
services,
body: contextBody,
id: contextBody.Context_UID
})
} else {
contextBody.WorkID = this.state.data.WorkID
PolicyModels.patchWorkContext({
user,
services,
body: contextBody,
id: contextBody.Context_UID
})
}
}
}
为此创建了以下测试,但我不断收到此消息: 期望(jest.fn())。toHaveBeenCalled() 预期的模拟函数已被调用。
const patchWorkMock = jest.fn();
PolicyModels.patchWorkContext = patchWorkMock;
beforeEach(() => (wrapper = mount(<MemoryRouter keyLength={0}><EditPolicy {...baseProps} /></MemoryRouter>)
it('Test patchPolicy function', async () => {
wrapper.setProps({
services:{},
user:{},
})
wrapper.find('EditPolicy').setState({
data:{
Policy:{},
Description:{},
Help_UID:{},
Choices:{},
WorkID:[],
WORK_CONTEXT:[],
},
});
wrapper.update();
wrapper.find('EditPolicy').instance().patchPolicy()
expect(patchWorkMock).toHaveBeenCalled();
return wrapper.find('EditPolicy').instance().patchPolicy().then(result =>
{
expect(result).toBeUndefined()
});
});
期待函数被调用/并正常工作。我能够通过测试,但是我相信它并没有增加任何内容。
答案 0 :(得分:0)
这是解决方案:
index.tsx
:
import React, { Component } from 'react';
import * as PolicyModels from './PolicyModels';
export interface IEditPolicyProps {
user: any;
services: any[];
}
interface IEditPolicyState {
data: {
WorkID: string;
Choices: string;
WORK_CONTEXT: any[];
};
Policy: string;
}
export class EditPolicy extends Component<IEditPolicyProps, IEditPolicyState> {
constructor(props: IEditPolicyProps) {
super(props);
this.state = {
data: {
WorkID: '',
Choices: '',
WORK_CONTEXT: []
},
Policy: ''
};
}
public async patchPolicy() {
const { user, services } = this.props;
const { data } = this.state;
const body = {
Policies: [
{
Choices: data.Choices || ''
}
]
};
PolicyModels.patchWork({
user,
services,
body,
id: this.state.Policy
});
const contextBody = data.WORK_CONTEXT[0];
const Context_UID = '';
const method = 'POST';
if (contextBody) {
//
if (contextBody.Context_UID) {
// If has UID, Patch
PolicyModels.patchWorkContext({
user,
services,
body: contextBody,
id: contextBody.Context_UID
});
} else {
contextBody.WorkID = this.state.data.WorkID;
PolicyModels.patchWorkContext({
user,
services,
body: contextBody,
id: contextBody.Context_UID
});
}
}
}
public render() {
return <div>Expected mock function to have been called -Async</div>;
}
}
PolicyModels.ts
:
export function patchWork(...args) {}
export function patchWorkContext(...args) {}
index.spec.tsx
:
import React from 'react';
import { ReactWrapper, mount } from 'enzyme';
import { MemoryRouter } from 'react-router';
import { EditPolicy, IEditPolicyProps } from './';
import * as PolicyModels from './PolicyModels';
describe('EditPolicy', () => {
let wrapper: ReactWrapper;
const baseProps: IEditPolicyProps = {
user: {},
services: []
};
beforeEach(() => {
wrapper = mount(
<MemoryRouter keyLength={0}>
<EditPolicy {...baseProps} />
</MemoryRouter>
);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('Test patchPolicy function with context body', async () => {
const patchWorkContextSpy = jest.spyOn(PolicyModels, 'patchWorkContext');
wrapper.find('EditPolicy').setState({
data: {
Policy: '',
Choices: '',
WorkID: '',
WORK_CONTEXT: [{ Context_UID: 1 }]
}
});
await (wrapper.find('EditPolicy').instance() as any).patchPolicy();
expect(patchWorkContextSpy).toBeCalledWith({ user: {}, services: [], body: { Context_UID: 1 }, id: 1 });
});
it('Test patchPolicy function without context body', async () => {
const patchWorkContextSpy = jest.spyOn(PolicyModels, 'patchWorkContext');
wrapper.find('EditPolicy').setState({
data: {
Policy: '',
Choices: '',
WorkID: '222',
WORK_CONTEXT: [{ Context_UID: 0, WorkID: 0 }]
}
});
await (wrapper.find('EditPolicy').instance() as any).patchPolicy();
expect(patchWorkContextSpy).toBeCalledWith({
user: {},
services: [],
body: { Context_UID: 0, WorkID: '222' },
id: 0
});
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/56238887/index.spec.tsx (12.167s)
EditPolicy
✓ Test patchPolicy function with context body (60ms)
✓ Test patchPolicy function without context body (4ms)
-----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 87.5 | 100 | 100 | |
PolicyModels.ts | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 87.5 | 100 | 100 | 50 |
-----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 14.746s
源代码:{{3}}
答案 1 :(得分:0)
您忘记在每次调用await
之前添加patchPolicy
了:
await wrapper
.find('EditPolicy')
.instance()
.patchPolicy();
顺便说一句,要知道测试是否正在检查每个expect
,一个好的做法是在测试的第一行中添加expect.assertions
。例如,如果您使用的是expect.assertions(2)
,则测试将失败。