微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 MERN 堆栈配置 Jest 测试?

如何解决如何使用 MERN 堆栈配置 Jest 测试?

我试图理解为什么玩笑测试会引发错误,这是我的代码: monogodb 连接:

const { MongoClient } = require('mongodb')
MongoClient.connect(
    process.env.MONGODB_URL,{
        useNewUrlParser: true,useUnifiedTopology: true,},async (error,client) => {
        if (error) {
            console.log('Unable to connect')
            throw error
        }
        console.log('MongoDB is connected!')

        //Global variable defined and will be reached by all scripts (routers) of App.js in server
        global.db = client.db(process.env.DATABASE_NAME)
    }
)

导致问题的测试脚本示例(还有另一个):

/* eslint-disable no-undef */
const request = require('supertest')
const app = require('../server/app-source')

test('Signup as a current user,so it will return 409 status code',async () => {
    await request(app)
        .post('/sign-up')
        .send({
            username: 'test user',password: 'test password',confirmPass: 'test password',email: 'test@test.com',role: 'Customer',})
        .expect(409)
})

test('Access the homepage as a user (test user which created above)',async () => {
    await request(app)
        .post('/login')
        .send({
            username: 'test user',})
        .expect(200)
})

test('Access the homepage as non-user',async () => {
    await request(app)
        .post('/login')
        .send({
            username: 'non-test user',password: 'non-test password',})
        .expect(404)
})

我收到以下错误无法读取 null 的属性 'JSON'ReferenceError: db is not defined。 在路由器 http 请求函数(后端)中的 catch 块中打印的两个错误。 当我在每个请求中连接到数据库时,测试都通过了,但它导致了很多延迟,所以我将其更改为这种格式,其中我将 'db' 变量定义为全局变量并且只连接到数据库一次。 重要的是要注意,客户端-服务器通信在网站本身中运行良好,这些错误仅在 Jest 测试中出现。 感谢帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。