使用Jest测试反应组件。 我想测试帖子中的突变。 突变是由按钮onclick事件触发的。 因此,我在其中调用了带有突变的函数。 它可以在网站上运行,但是当我使用Jest为该组件编写单元测试时,它无法正常工作。 我从中引用了- https://www.apollographql.com/docs/react/development-testing/testing/ https://github.com/apollographql/apollo-client/issues/6452
获取错误
TypeError:xMutation不是函数
178 | onResumeState = () => {
179 | const { xMutation } = this.props;
> 180 | xMutation().then(({ data }) => {
| ^
181 | const { x: { success } } = data;
182 | if (success) {
183 | this.setState({ playState: true });
x.query.js
export const xMutation = gql`
mutation xMutation($xId: String!) {
y(xId: $xId){
...on SuccessActionResponse {
z{
id
}
message
success
}
...on ErrorResponse{
message
success
}
}
}
`;
export const xMutationParams = {
options: props => (
{
variables: {
xId: props.xId,
},
refetchQueries: () => [{
query: getxQuery,
fetchPolicy: 'network-only',
variables: {
id: props.xId,
},
}],
}
),
name: 'xMutation',
};
x.test.js
const mocks = [
{
request: {
query: xMutation,
fetchPolicy: 'network-only',
variables: { xId: 'eb1bcc5c-9f17-409c-8b23-356c5523b5f0' },
},
result: {
data: {
xData: {
id: 2,
yId: 2,
},
message: 'Resumed Successfully',
success: true,
},
},
},
];
describe('X component', () => {
const { headerData } = defaultProps;
render(
<MockedProvider mocks={mocks} addTypename={false}>
<StatusTab {...headerData} />
</MockedProvider>,
);
test('should render pause/play state', async () => {
const linkText = 'yyy';
expect(screen.getByText(`(${linkText})`)).toBeInTheDocument();
// await new Promise(resolve => setTimeout(resolve, 0));
await act(async () => {
fireEvent.click(screen.getByText(`(${linkText})`));
});
}
});
});
x.jsx
onResumeState = () => {
const { xMutation } = this.props;
xMutation().then(({ data }) => {
const { x: { success } } = data;
if (success) {
this.setState({ playState: true });
}
});
}
答案 0 :(得分:0)
我对此并不陌生,因此搞砸了。我不需要为此使用Mocked Provider。只能使用模拟功能。 这是更新的x.test.jsx,可以正常工作-
const defaultProps = {
headerData: {
..., // Different props
// Added mock function
xMutation: jest.fn().mockImplementation(
() => Promise.resolve({ data: { xAssignment: { success: true } } }),
),
},
};
describe('StatusTab component', () => {
const { headerData } = defaultProps;
render(<StatusTab {...headerData} />);
test('should render pause/play state', async () => {
expect(screen.getByText(`(${resumeText})`)).toBeInTheDocument();
expect(screen.getByLabelText(`${xText}`)).toBeDisabled();
await act(async () => {
fireEvent.click(screen.getByText(`(${resumeText})`));
});
expect(screen.getByText(`(${pausedText})`)).toBeInTheDocument();
expect(screen.getByLabelText(`${xText}`)).not.toBeDisabled();
});
});
如果您想在玩笑中使用graphql阿波罗突变,这是一个很好的参考-https://www.apollographql.com/docs/react/development-testing/testing/