【发布时间】:2019-03-24 10:45:38
【问题描述】:
我在特定路由上调用了以下函数,我正在尝试测试是否使用特定参数调用内部的 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' -
我试过了,但由于某种原因,用户然后返回空对象。这样我至少可以看到正确的输出。
-
文件
../models/model.user是什么样的? -
文件正常,功能正常,只是无法进行测试。无论如何,我明天会用用户模式更新我的问题。
-
你在所有的移动代码中都是正确的,最后我没有导出模型,只是注册。因此,如果您将其创建为答案,我将很乐意接受。
标签: javascript node.js mongoose mocha.js sinon