javascript - Jest ReferenceError:您正在尝试在 Jest 环境被拆除后“导入”文件
问题描述
我正在尝试使用 jest 测试我的 API。
每次运行测试后都会显示此错误
PASS test/auth.test.js
√ Create a new user (237 ms)
√ SignIn with user (133 ms)
√ Delete The user (144 ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 2.173 s, estimated 8 s
Ran all test suites.
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
我的测试文件
const auth = require("../routes/auth");
const fetch = require('node-fetch');
fetch.Promise = require("bluebird");
(async () => {
beforeAll(done =>{
jest.useFakeTimers();
done();
})
afterAll(done => {
done();
})
jest.setTimeout(10000)
test("Create a new user", async () => {
const status = await fetch(URL + "/api/auth/signUp", {
method:"POST",
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body:JSON.stringify(SignUpReq)
})
.then(res => res.status)
await expect(status).toBe(201);
})
test("SignIn with user", async () => {
let status = await fetch(URL + "/api/auth/signin", {
method:"POST",
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body:JSON.stringify(deleteUserReq)
})
.then(res => res.status)
await expect(status).toBe(200);
})
test("Delete The user", async () => {
const status = await fetch(URL + "/api/auth/deleteUser", {
method:"DELETE",
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Bearer <token>'
},
body:JSON.stringify(deleteUserReq)
})
.then(res => res.status)
await expect(status).toBe(200);
})
})()
API 测试实际数据库,而不是模拟数据库
我试过了
猫鼬.connection.close()
jest.useFakeTimers();
更改笑话超时
毕竟之前和之后添加完成
在每个期望之前使用等待
仍然出现错误
我的环境:
"node": "V12.19.0"
"bcrypt": "^5.0.0",
"bluebird": "^3.7.2",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"md5": "^2.3.0",
"mongoose": "^5.11.8",
"node-fetch": "^2.6.1",
"jest": "^26.6.3"
我的数据库托管在 mongo atlas
如何删除此错误消息?
解决方案
推荐阅读
- java - 支持这两种基本身份验证的应用程序。和 SAML - Spring Security - Spring MVC(无引导)
- flutter - 颤振互联网地址。查找总是返回连接真
- python - 有没有办法在 Python 程序 .exe(通过 pyinstaller)中包含“chromedriver.exe”?
- macos - 尝试连接到 AWS EC2 时,VMWare Horizon 7 客户端超时
- r - 用列内类的平均值替换缺失值
- php - 我无法得到审讯的结果。(postgresql 和 php)
- ios - Swift:为浏览器创建搜索栏
- python - 使用 Pandas 创建一个矩阵,其中包含一组列范围和一组行范围
- python-3.x - 在 Jupyter Notebook 上导入 python 3.8.2 环境时所有模块的 ModuleNotFoundError
- version - 如何安装最新版本的 pytest,与旧版本共存?