Я пытаюсь использовать подход TDD для пользовательского API.Я хотел интегрировать модульные тесты для своих функций: userRegister и userLogin
Это мой app.js
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const passport = require('passport')
const users = require('../routes/users')
const app = express()
const port = 5000
app.get('/', (req, res) => {
res.send({ msg: 'Test' })
})
//BodyParser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//Passport middleware
app.use(passport.initialize())
//Initialize Routes
app.use('/api/users', users)
//Export app
module.exports = app
Это мой userController.js:
'use strict'
const express = require('express')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const keys = require('../../../../config/keys')
const passport = require('passport')
const status = require('http-status-codes')
const User = require('../../models/User')
module.exports.test = (req, res) => {
res.json({msg: 'Users works'})
}
module.exports.userRegister = (req, res) => {
User.findOne({ email: req.body.email})
.then(user => {
if(user)
return res.status(400).json({ userEmailerror: 'Email already
exists'})
else{
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
})
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err))
}
})
}
это мой userController.test.js
'use strict'
const mongoose = require('mongoose')
const testUserDB = require('../../../config/keys').testUsersMongURI
mongoose.connect(testUserDB)
const userController = require('../modules/controllers/userController')
const User = require('../models/User')
describe('register new user', () => {
test('succesfully register a valid user', () => {
const newUser = new User({
name: 'test',
email: 'test@gmail.com',
password: 'test123'
})
const req = {body: {newUser}}
userController.userRegister(req).then(user => {
expect(user.name).toBe('test')
expect(user.email).toBe('test@gmail.com')
})
})
})
Сценарий, который я использую для запуска теста:
"test": "jest --coverage",
Я новичок в Javascript и полном стеке, и ошибка, которую я получил,смущает меня
RUNS src/user/__tests__/userController.test.js
FAIL src/user/__tests__/userController.test.js
register new user
× succesfully register a valid user (19ms)
● register new user › succesfully register a valid user
TypeError: Cannot read property 'then' of undefined
16 | })
17 | const req = {body: {newUser}}
> 18 | userController.userRegister(req).then(user => {
| ^
19 | expect(user.name).toBe('test')
20 | expect(user.email).toBe('test@gmail.com')
21 |
at Object.test (src/user/__tests__/userController.test.js:18:3)
Спасибо за вашу помощь!