我的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上找到它。
非常感谢任何帮助
答案 0 :(得分:0)
所以我找到了解决方案
导入不应该是
import { RequestType, networkClient} from './path/to/NetworkClient';
但是应该像这样要求模块:
const network = require('./../../../../networking/NetworkClient');
之后,我可以成功模拟实现并完成测试:
const testFeed = { items: feed, token: 'nextpage' };
network.networkClient = jest.fn(() => {
return testFeed;
});
我希望它有助于某人