【发布时间】: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