gpt4 book ai didi

node.js - 测试时如何修复这个 "Cannot read property of undefined"?

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:32 26 4
gpt4 key购买 nike

我正在尝试使用 Jest 对此 Nodejs API 运行测试。尽管当我运行应用程序时一切正常,但它失败并返回错误

TypeError: Cannot read property 'store' of undefined

测试代码:

const request = require('supertest')

const server = require('../../server')
const { User } = require('../../app/models/User')

describe('User', () => {
test('should create user', async () => {
const user = await User.store({
name: 'Marcelo',
email: 'marcelo@vuttr.com',
password: '123456'
})

const response = await request(server)
.post('/user')
.send({
name: user.name,
email: user.email,
password: user.password
})

expect(response.status).toBe(200)
})
})

Controller :

const User = require('../models/User')

class UserController {
async store (req, res) {
const { email } = req.body

if (await User.findOne({ email })) {
return res.status(400).json({ error: 'User already exists' })
}

const user = await User.create(req.body)

return res.json(user)
}
}

module.exports = new UserController()

有关更多详细信息,我分享 this project in github

最佳答案

试试这个代码

测试代码

const request = require('supertest')

const server = require('../../server')
const { User } = require('../../app/models/User')
const { UserController } = require('../../UserController')

describe('User', () => {
test('should create user', async () => {
const user = await UserController({
name: 'Marcelo',
email: 'marcelo@vuttr.com',
password: '123456'
})

const response = await request(server)
.post('/user')
.send({
name: user.name,
email: user.email,
password: user.password
})

expect(response.status).toBe(200)
})
})

Controller :

const User = require('../models/User')

const UserController = async(req, res) => {
const { email } = req.body
if (await User.findOne({ email })) {
return res.status(400).json({ error: 'User already exists' })
}

const user = await User.create(req.body);

return res.status(201).json(user);
}

module.exports = UserController;

关于node.js - 测试时如何修复这个 "Cannot read property of undefined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55969523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com