I'm trying to run a test using Jest for this Nodejs API. Although everything works when I run the app, it's failing and returning the error

TypeError: Cannot read property 'store' of undefined

The test code:

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: '[email protected]',
      password: '123456'
    })

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

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

The 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()

For more details, I share this project in github.

1 Answers

0
Ashish Patidar On

try this code

the Test Code

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: '[email protected]',
      password: '123456'
    })

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

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

The 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;