【发布时间】:2019-08-24 00:06:42
【问题描述】:
我对测试很陌生,尤其是 Jest。 我正在关注几个教程,它们以我尝试的方式处理异步代码。当我制作一个用虚拟数据解析的自定义 Promise 时,我的代码似乎可以工作。但是当我尝试使用 axios 从外部 API 中获取数据时,Jest 会得到未定义的响应。
// functions2.js
const axios = require("axios")
const fetch = () => {
axios.get("https://jsonplaceholder.typicode.com/users")
.then(res => res.data)
.catch(err => err);
}
module.exports = fetch;
// functions2.test.js
describe("async operation", ()=>{
it("should be defined", ()=>{
expect(fetch).toBeDefined()
}); // Passed
it("should fetch", async () => {
expect.assertions(1);
const data = await fetch();
expect(data).toBeTruthy();
}) // Did not pass, data is undefined
it("should fetch, using promises", () => {
expect.assertions(1);
return fetch().then(data => {
expect(data).toBeTruthy();
}) // Did not pass, got 0 assertions
})
})
在一个教程中我遇到这与 Jest 通过 Node.JS 运行有关,但我不知道如何处理它,因为我不知道 node.js。
另外,我遵循 Traversy Media 的教程,克隆了他的 Git 存储库 (https://github.com/bradtraversy/jest_testing_basics) 并遇到了同样的问题(尽管在视频中它有效)
【问题讨论】:
标签: jestjs