我使用 NockJS 和 Jest 为 React 应用程序编写了一个简单的 API 调用单元测试,如下所示:
AjaxService.js
export const AjaxService = {
post: (url, data, headers) => {
return axios({
method: "POST",
url: url,
headers: headers || { "content-type": "application/json" },
data: data
});
},
};
Run Code Online (Sandbox Code Playgroud)
API承诺:
export const getDashboard = (request) => {
return AjaxService.post(API_DASHBOARD_URL + "/getDashboard", request
).then(
response => {
return response.data;
},
(error) => {
return error.response.data;
}
)
};
Run Code Online (Sandbox Code Playgroud)
使用NockJS进行单元测试:
nock(baseUrl)
.post(subUrl, request)
.reply(200, response);
getDashboard(request)
.then(resp => {
let compareVal = …Run Code Online (Sandbox Code Playgroud)