Sinon 存根一个公理帖子,返回值未定义且无法解析



待测试的函数

export const get_drawing_data = (url, request_obj) => {
axios
.post(url, JSON.stringify(request_obj), {
headers: {
// Overwrite Axios's automatically set Content-Type
"Content-Type": "application/json",
},
})
.then((response) => {
return response;
})
.catch((error) => {
console.log(error);
});
};

Sinon存根用于拦截Axios的post呼叫。它模拟axios.post返回值,该值是Promise。Promise的解析将API响应数据作为一个值。所以下面这行使用sinon.stub解析函数创建的promise作为axiospost函数的返回值。

describe("test axios get_drawing_data", () => {
it("test input and output", () => {
const requestData = {a: "hello world"};
const responseData = "hellow world";
sinon.stub(axios, "post").resolves(responseData);
const response = get_drawing_data("http://127.0.0.1/xxx", requestData);
expect(response).toEqual(["hello world"]);
});
});

期望值是response.data应该等于Promise中的构造值。但实际上它是一个未定义的。

expect(received).toEqual(expected) // deep equality
Expected: ["hello world"]
Received: undefined

这里有一些问题。。。

  1. 您的get_drawing_data函数不返回任何内容
  2. Axios默认值已经非常适合在没有自定义标头或有效负载转换的情况下发布JSON
  3. 不要捕捉拒绝承诺的情况,并将承诺转换为已解决的承诺,尤其是通过使用undefined值进行解决。您的消费者将无法正确处理该响应
  4. 您可能对Axios响应data比对整个响应更感兴趣
  5. 您应该等待调用get_drawing_data()的结果
  6. 当你已经告诉数组返回什么时,不确定为什么你会期望它

考虑到这一点,请尝试以下

export const get_drawing_data = async (url, request_obj) => {
try {
const { data } = await axios.post(url, request_obj);
return data;
} catch (err) {
console.error("get_drawing_data", err.toJSON());
throw err; // keep the promise chain rejected
}
};

或者如果你不喜欢async / await。。。

// note the arrow function has no `{...}`, ie an implicit return
export const get_drawing_data = (url, request_obj) =>
axios
.post(url, request_obj)
.then(({ data }) => data)
.catch((err) => {
console.error("get_drawing_data", err.toJSON());
return Promise.reject(err); // keep the promise chain rejected
});

在你的测试

describe("test axios get_drawing_data", () => {
it("test input and output", async () => { // async function here
const url = "http://127.0.0.1/xxx";
const requestData = { a: "hello world" };
const responseData = "hellow world";
// resolve with something closer to the Axios response schema
sinon.stub(axios, "post").resolves({ data: responseData });
// await the result
const response = await get_drawing_data(url, requestData);
// verify the stub was called as expected
sinon.assert.calledWith(axios.post, url, requestData);
// compare the response with what you actually set up
expect(response).toEqual(responseData);
});
});

相关内容

  • 没有找到相关文章

最新更新