【问题标题】:Mocking a HttpClient with Jest用 Jest 模拟 HttpClient
【发布时间】:2019-12-10 18:32:20
【问题描述】:

我的 React Native + Jest + Typescript 设置有问题。

我正在尝试测试 thunk/network 操作。我创建了一个 networkClient 函数:

export const networkClient = async (
  apiPath: string,
  method = RequestType.GET,
  body = {},
  authenticate = true,
  appState: IAppState,
  dispatch: Dispatch<any>
) => {
    ... validate/renew token, validate request and stuff...

    const queryParams = {
      method,
      headers: authenticate
        ? helpers.getHeadersWithAuth(tokenToUse)
        : helpers.getBaseHeaders(),
      body: method === RequestType.POST ? body : undefined,
    };
    const fullUri = baseURL + apiPath;

    const result = await fetch(fullUri, queryParams);
    if (result.ok) {
      const json = await result.json();
      console.log(`Result ${result.status} for request to ${fullUri}`);
      return json;
    } else {
      ... handle error codes
    }
  } catch (error) {
    handleNetworkError(error, apiPath);
  }
};

现在,当我为使用上面的 networkClient 请求服务器数据的操作编写测试时,如下所示:

  const uri = `/subscriptions/media` + tokenParam;
  const json = await networkClient(
    uri,
    RequestType.GET,
    undefined,
    true,
    getState(),
    dispatch
  );

我想模拟实现以返回模拟响应 pr。测试。

作为公关文档,我认为可以这样做:

import { RequestType, networkClient} from './path/to/NetworkClient';

在测试中:

networkClient = jest.fn(
  (
    apiPath: string,
    method = RequestType.GET,
    body = {},
    authenticate = true,
    appState: IAppState,
    dispatch: Dispatch<any>
  ) => {
    return 'my test json';
  }
);

const store = mockStore(initialState);
return store
      .dispatch(operations.default.getMoreFeedData(false))
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions);
        expect(store.getState().feedData).toEqual(testFeed);
        // fetchMock.restore();
      });

但是networkClient没有定义,ts告诉我

[ts] Cannot assign to 'networkClient' because it is not a variable.

我做错了什么?我一定错过了一些关于 Jest 如何模拟模块以及如何在某处提供模拟实现的信息,但我在文档和 Google/SO 上都找不到它。

非常感谢任何帮助

【问题讨论】:

  • automock=false,顺便说一句

标签: reactjs unit-testing redux mocking jestjs


【解决方案1】:

所以我找到了解决办法

导入不应该是

import { RequestType, networkClient} from './path/to/NetworkClient';

但是应该像这样需要模块:

const network = require('./../../../../networking/NetworkClient');

之后,我可以成功地模拟实现并完成测试:

const testFeed = { items: feed, token: 'nextpage' };
network.networkClient = jest.fn(() => {
  return testFeed;
});

希望对大家有所帮助

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2020-04-21
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2019-08-17
    • 2023-04-02
    相关资源
    最近更新 更多