Mocha + Sinon 测试猫鼬方法被调用

Mocha + Sinon testing mongoose methods being called

我在特定路由上调用了以下函数,我正在尝试测试是否使用特定参数调用了内部的 mongoose 方法。 我的代码:

import boom from 'boom'
import User from '../models/model.user'


export const getSingle = async (req, res, next) => {
    try {
        const user = await User.findById(req.payload.id, '-auth')
        if (user) {
            return res.json({user})
        }
        return next(boom.notFound('User not found'))
    } catch (err) {        
        return next(boom.badImplementation('Something went wrong', err))
    }
}

我的测试用例:

process.env.NODE_ENV = 'test'
import 'babel-polyfill'
import mongoose from 'mongoose'
import sinon from 'sinon'
require('sinon-mongoose')
import { getSingle } from '../src/controllers/controller.user'
const User = mongoose.model('User')


describe('User Controller ----> getSingle', () => {
    it('Should call findById on User model with user id', async () => {
        const req = {
                    payload: {
                        id: '123465798'
                    }
                }
        const res = { json: function(){} }
        const next = function() {}
        const UserMock = sinon.mock(User)

        UserMock.expects("findById").once().withExactArgs('123465798', '-auth')
        await getSingle(req, res, next)           
        UserMock.verify()



    })
})

它没有通过测试,因为即使调用了方法也没有调用。

在测试中导入与被测代码中使用的模型相同的模型,即 ../models/model.user 它应该按预期工作。