首页 > 解决方案 > 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

如何删除此错误消息?

标签: javascriptnode.jstestingmongoosejestjs

解决方案


推荐阅读