redux 操作的玩笑单元测试
我试图通过为我的操作编写所有可能的单元测试来实现 100% 的代码覆盖率。 以下是我的操作代码
export const getData = async (
requestUUID: string,
dispatch?: (type?: { type: string, payload?: unknown }) => {
type: string,
payload?: unknown,
}
): Promise<Cart> => {
const url = `${getApiUrl()}${API_V1_CART}`;
dispatch({ type: GET_REQUEST });
try {
const result = await apiCall(
{
method: "GET",
withCredentials: true,
url,
timeout: 1000,
},
dispatch,
requestUUID
);
dispatch({ type: GET_SUCCESS, payload: result });
return result;
} catch (e) {
dispatch({ type: GET_FAILED, payload: e });
return e;
}
};
我为上述操作编写了一个单元测试,如下所示
describe('getData', () => {
describe('success', () => {
let result;
const mockDispatch = jest.fn();
const mockData = {};
beforeAll(async () => {
(apiCall as jest.Mock).mockResolvedValueOnce(mockData);
result = await getBasketData('uuid', mockDispatch);
});
it('should call the correct api', () => {
expect(apiCall).toHaveBeenCalledWith(
{
method: 'GET',
timeout: 1000,
url: 'http://localhost/api/v1/data',
withCredentials: true,
},
mockDispatch,
'uuid',
);
});
it('should return the correct result', () => {
expect(result).toEqual(mockData);
});
});
});
该测试仅覆盖了77.78%的代码覆盖率。我可以为此编写哪些其他测试来实现 100% 的代码覆盖率?
I'm trying to achieve 100% code coverage by writing all possible unit tests for my action.
The following is my action code
export const getData = async (
requestUUID: string,
dispatch?: (type?: { type: string, payload?: unknown }) => {
type: string,
payload?: unknown,
}
): Promise<Cart> => {
const url = `${getApiUrl()}${API_V1_CART}`;
dispatch({ type: GET_REQUEST });
try {
const result = await apiCall(
{
method: "GET",
withCredentials: true,
url,
timeout: 1000,
},
dispatch,
requestUUID
);
dispatch({ type: GET_SUCCESS, payload: result });
return result;
} catch (e) {
dispatch({ type: GET_FAILED, payload: e });
return e;
}
};
I have written a unit test for the above as action as follows
describe('getData', () => {
describe('success', () => {
let result;
const mockDispatch = jest.fn();
const mockData = {};
beforeAll(async () => {
(apiCall as jest.Mock).mockResolvedValueOnce(mockData);
result = await getBasketData('uuid', mockDispatch);
});
it('should call the correct api', () => {
expect(apiCall).toHaveBeenCalledWith(
{
method: 'GET',
timeout: 1000,
url: 'http://localhost/api/v1/data',
withCredentials: true,
},
mockDispatch,
'uuid',
);
});
it('should return the correct result', () => {
expect(result).toEqual(mockData);
});
});
});
This test only covers 77.78% of code coverage. What are the other tests i can write for this to achieve 100% code coverage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为 catch 块编写测试。
You can write test for the catch block.