如何模拟redux中测试动作创建者的qraphQL/Apolo查询响应



由于我对graphQL/Apollo没有太多经验,用Jest测试时嘲笑查询响应让我感到困惑。我有以下动作创建者:

export const fetchSomething = _id => (dispatch) => {
client.query({
query: gql`
{
something(_id: "${_id}") {
_id
somedata
}
}`,
})
.then(something => dispatch({
type: FETCH_SOMETHING,
payload: something.data,
}));
};

下面的测试不起作用

describe('fetchSomething', () => {
it('should dispatch correct type and data correctly', async () => {
const dispatch = jest.fn();
client.query =
async () => new Promise(resolve => resolve({ something: 'something' }));
await fetchSomething('xxx')(dispatch);
expect(dispatch).toHaveBeenCalledWith({ type: FETCH_SOMETHING,   payload: {something: 'something');
});
});

我的的ApolloClient.js文件

import ApolloClient from 'apollo-boost/lib/index.umd';
const client = new ApolloClient({
uri: 'http://localhost:5000/graphql',
});
export default client;

通常,对于像fetch这样的方法,解析promise来模拟响应就足够了。这对graphql/apollo现在不起作用。在这种情况下,我该如何嘲笑回应?

提前感谢

我看到两个问题:

1-您没有返回client.query承诺,所以测试中的await fetchSomething实际上并没有等待该承诺返回,然后再转到expectreturn client.query应该解决这个问题。

2-您可能还需要将客户端注入到动作创建者中。redux-thunk有一个withExtraArgument选项,可以让您做到这一点。当您创建redux存储并应用中间件时,您可以通过实际的Apollo客户端,然后在测试中,您可以使用模拟的query:通过client

await fetchSomething('xxx')(dispatch, _, client); // the 2nd argument (getState) is unused

https://github.com/reduxjs/redux-thunk

最新更新