我正在尝试使用Jest为此Nodejs API运行测试。尽管当我运行该应用程序时一切正常,但是它失败并返回错误
TypeError:无法读取未定义的属性“ store”
测试代码:
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)
})
})
控制器:
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。
答案 0 :(得分:0)
尝试此代码
测试代码
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)
})
})
控制器:
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;