微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未调用模拟 res.status 上的快速控制器 getAllUsers 函数的 Jest 单元测试失败?

如何解决未调用模拟 res.status 上的快速控制器 getAllUsers 函数的 Jest 单元测试失败?

嗨,朋友们,在我的测试中,我正确地模拟了 express res 但 res.status 断言失败,我想不出明确的解释。 您有什么建议吗,谢谢您的帮助?

注意:getAllusers 中的 if 分支不是我已经评论它的原因,仍然是相同的结果。 但如果我替换了 getAllusers 函数中的代码行:

const usersCount = await User.count({})

与:

const usersCount = 2

所有测试都通过。

不知何故在 getAllUsers 中调用两个异步函数会导致这种行为???

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

exports.getAllUsers = catchAsync(async (req,res,next) => {
  const { start = 0,limit = 7 } = req.query
  const usersCount = await User.count({})
  res.set('Access-Control-Expose-Headers','X-Total-Count')
  res.set('X-Total-Count',`${usersCount}`)
  const users = await User.findAll({
    attributes: ['id','username','email','role','avatar'],limit: limit * 1,offset: start * 1
  })
  if (!usersCount) {
    return next(new AppError('no data found',204))
  }

  res.status(200).json({
    status: 'success',data: users
  })
})
exports.getUser = catchAsync(async (req,next) => {
  const user = await User.findOne({
    attributes: ['id',where: {
      id: req.params.id * 1
    }
  })
  if (!user) {
    return next(new AppError('user not found',404))
  }
  res.status(200).json({
    status: 'success',data: user
  })
})
exports.deleteUser = catchAsync(async (req,next) => {
  const user = await User.destroy({
    where: {
      id: req.params.id * 1
    }
  })
  if (!user) {
    return next(new AppError('user not found',data: user
  })
})
exports.updateUser = catchAsync(async (req,next) => {
  if (req.body.password) {
    req.body.password = bcrypt.hashSync(req.body.password,10)
  }
  const user = await User.update(
    { ...req.body },{
      where: {
        id: req.params.id * 1
      },returning: true
    }
  )
  if (!user[0]) {
    return next(new AppError('user not found',404))
  }
  const { id,username,email,role,avatar } = user[1][0]
  res.status(200).json({
    status: 'success',data: { id,avatar,role }
  })
})

这是测试:

const userController = require('./userController')
const AppError = require('../utils/appError')
const db = require('../models')

jest.mock('../models')
describe('UserController',() => {
  afterEach(() => {
    //jest.clearallMocks()
    // Reset to original implementation before each test
  })
  test('Expect to respond with 200 code and users data',async () => {
    const users = [{ username: 'han' },{ username: 'med' }]
    db.User.findAll = jest
      .fn()
      .mockImplementation(() => Promise.resolve([...users]))
    db.User.count = jest.fn().mockImplementation(() => Promise.resolve(2))
    const req = { query: {} }
    const res = {
      status: jest.fn(() => res),json: jest.fn()
    }
    res.set = jest.fn()
    const next = jest.fn()
    await userController.getAllUsers(req,next)
    expect(next).not.toHaveBeenCalled()
    expect(res.status).not.toHaveBeenCalled()
    expect(db.User.count).toHaveBeenCalledTimes(1)
    expect(db.User.count).toHaveBeenCalledWith({})
    expect(db.User.findAll).toHaveBeenCalledTimes(1)
    expect(db.User.findAll).toHaveBeenCalledWith({
      attributes: ['id',limit: 7,offset: 0
    })
    expect(res.set).toHaveBeenCalledTimes(2)
    expect(res.set.mock.calls[0][0]).toBe('Access-Control-Expose-Headers')
    expect(res.set.mock.calls[0][1]).toBe('X-Total-Count')
    expect(res.set.mock.calls[1][0]).toBe('X-Total-Count')
    expect(res.set.mock.calls[1][1]).toBe('2')
    expect(res.status).toHaveBeenCalledTimes(1)
    expect(res.status).toHaveBeenCalledWith(200)
    expect(res.json).toHaveBeenCalledTimes(1)
    expect(res.json).toHaveBeenCalledWith({
      status: 'success',data: users
    })
  })
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。