包含异步调用 User.findAll [sequelize postgresql] 的函数的 Jest 测试失败?

时间:2021-06-23 20:11:23

标签: javascript node.js express jestjs

我正在尝试向 getAllUsers 函数添加测试,但我不知道为什么测试失败? 我认为断言是在对 User.findAllfinishes 的所有异步调用之前运行的!!! 你有什么建议吗? this is result of the test

这是正在测试的文件:

const { Op } = require('sequelize')
const { User } = require('../models')
const catchAsync = require('../utils/catchAsync')
const AppError = require('../utils/appError')

exports.getAllUsers = catchAsync(async (req, res, next) => {
  const users = await User.findAll({
    attributes: ['id', 'username', 'email', 'role', 'avatar'],
    where: {
      id: { [Op.gt]: 0 }
    }
  })
  if (!users.length) {
    return next(new AppError('no data found', 204))
  }
  res.status(200).json({
    status: 'success',
    data: users
  })
})

这是测试代码:

const userController = require('../controllers/userController')

describe('UserController', () => {
  const users = [
    {
      username: 'Admin',
      role: 'admin',
      avatar: 'bb',
      email: 'admin@gmail.com'
    },
    {
      username: 'User',
      role: 'user',
      avatar: 'bb',
      email: 'user@gmail.com'
    }
  ]
  test('Expect to respond with 200 code and users data', async () => {
    const req = {}
    const res = { status: jest.fn(() => res), json: jest.fn(() => res) }
    const next = jest.fn()
    await userController.getAllUsers(req, res, next) 
    expect(res.status).toHaveBeenCalledTimes(1)
    expect(res.status).toHaveBeenCalledWith(200)
    expect(res.json).toHaveBeenCalledTimes(1)
    expect(res.json).toHaveBeenCalledWith({
      status: 'success',
      data: users
    })
  })
})

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

考虑到问题中没有未共享的先决条件(模拟数据库)

当您运行 jest --coverage 时,它会生成一份覆盖率报告,让您大致了解代码执行情况

enter image description here

上面可以看到if语句没有被执行,意思是从User.findAll抛出错误

要解决此问题:您可以模拟 User 模型,findAll 的已解决值可以解决此问题

const userController = require('../controllers/userController');
const { User } = require('../models');

// generate auto-mock of the module
jest.mock('../models');

describe('UserController', () => {
  const users = [
    // .... same as in the question
  ];
  beforeAll(() => {
    // give the mock function a value
    // for the promise to be resolved with
    User.findAll.mockResolvedValue(users);
  });

  test('Expect to respond with 200 code and users data', async () => {
    // .... same as in the question
  });
});
相关问题