【问题标题】:How to mock qraphQL/Apollo query response for testing action-creator in redux?如何模拟 graphQL/Apollo 查询响应以在 redux 中测试 action-creator?
【发布时间】:2019-04-07 23:19:07
【问题描述】:

由于我没有太多使用 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。在这种情况下如何模拟响应?

提前致谢

【问题讨论】:

标签: reactjs testing redux graphql jestjs


【解决方案1】:

我看到 2 个问题:

1 - 您没有返回client.query 承诺,因此测试中的await fetchSomething 实际上并没有等待该承诺返回,然后再继续使用expectreturn client.query 应该可以解决这个问题。

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

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

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

【讨论】:

  • tnx,试试看
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 2021-08-28
  • 2020-08-17
  • 2018-09-27
  • 2016-05-26
  • 2019-06-17
  • 2017-07-30
  • 2020-10-05
相关资源
最近更新 更多