jestjs - 对 API 的异步请求在 Jest 中返回未定义
问题描述
我对测试很陌生,特别是对 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
})
})
在一个教程中,我遇到这与通过 Node.JS 运行的 Jest 有关,但我不知道如何处理它,因为我不知道 node.js。
此外,我遵循 Traversy Media 的教程,克隆了他的 Git 存储库(https://github.com/bradtraversy/jest_testing_basics)并遇到了同样的问题(尽管在视频中它有效)
解决方案
问题是因为您没有从fetch
.
将您的更新functions2.js
为:
const fetch = async () => {
return axios
.get("https://jsonplaceholder.typicode.com/users")
.then(res => res.data)
.catch(err => err);
};
希望能帮助到你。
推荐阅读
- android - APK 文件的未来
- kubernetes - 用于网络策略的 Kubernetes 列表式标签值
- go - 一次清除 pilosa 字段中设置的所有位
- r - 如何从R中的列按自定义顺序排列行
- postgresql - LIMIT 的 Postgres 动态值
- css - 我需要使用 FlexBox 将第一列设为特定宽度吗?
- python - 如何删除元素“
我有一个要删除 element 的 html
<div> <div style
。我尝试了下面的代码,但无济于事for d in soup.select('div > div.style'): d.extract()
您能否详细说明
- ansible - Ansible:在嵌套字典变量中查找属性
- php - 条纹 | 发票地址未出现在发票 pdf 上
- php - Laravel 资源跳过关系