【发布时间】:2020-11-24 04:46:47
【问题描述】:
使用 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 });
}
});
}
【问题讨论】:
-
Graphql 查询可以通过 webpack 插件进行转译,以在运行时跳过解析和编译。看起来您的测试缺少必要的预处理。尝试使用
useQuery而不是().then
标签: reactjs unit-testing jestjs