iam*_*wtk 6 javascript mongoose mongodb node.js
我正在测试我的应用程序,需要验证是否使用正确的数据调用了mongoose模式构造函数.
让我说我这样做:
const UserData = new User(user)
console.log(UserData.contructor.args)
Run Code Online (Sandbox Code Playgroud)
我希望user对象的日志.可能数据传递给mongoose模式的构造函数?
有人可以告诉我如何访问它?
这是我试图解决的具体案例.
export const signup = async (req, res, next) => {
try {
//if user object is missing return error
if (!req.body.user)
return next(boom.unauthorized('No user data received.'))
//get user data
const user = req.body.user,
{ auth: { local: { password, password_2 } } } = user
//check if both passwords match
if (password !== password_2)
return next(boom.unauthorized('Passwords do not match.'))
//check if password is valid
if (!Password.validate(password)) {
const errorData = Password.validate(password, { list: true })
return next(boom.notAcceptable('Invalid password.', errorData))
}
//creates new mongo user
const UserData = new User(user)
//sets user password hash
UserData.setPassword(password)
//saves user to database
await UserData.save()
//returns new users authorization data
return res.json({ user: UserData.toAuthJSON() })
} catch(err) {
//if mongo validation error return callback with error
if(err.name === 'ValidationError') {
return next(boom.unauthorized(err.message))
}
// all other server errors
return next(boom.badImplementation('Something went wrong', err))
}
}
Run Code Online (Sandbox Code Playgroud)
部分测试:
describe('Success', () => {
it('Should create new instance of User with request data', async () => {
const req = { body },
res = {},
local = { password: '1aaaBB', password_2: '1aaaBB'},
constructorStub = sandbox.stub(User.prototype, 'constructor')
req.body.user.auth.local = {...local}
await signup(req, res, next)
expect(constructorStub.calledOnceWith({...req.body.user})).to.be.true
})
})
Run Code Online (Sandbox Code Playgroud)
编辑:我可以验证是否被调用 expect(constructorStub.calledOnce).to.be.true
只是无法验证传递的数据.
编辑:经过一段时间的交谈,听起来您需要的是验证您是否正确创建了新用户。
我的建议是创建一个新函数createUserFromRequest来接收request并返回new User.
然后您可以轻松测试这个函数,因为它是纯粹的(没有副作用,只有输入和输出)。
此时,处理程序中的大部分逻辑都在这个函数中,因此可能不值得测试处理程序本身,但您仍然可以这样做,例如通过模拟上面的函数。
例子:
function createUserFromRequest(request) {
//get user data
const user = req.body.user,
{ auth: { local: { password, password_2 } } } = user
//check if both passwords match
if (password !== password_2)
return next(boom.unauthorized('Passwords do not match.'))
//check if password is valid
if (!Password.validate(password)) {
const errorData = Password.validate(password, { list: true })
return next(boom.notAcceptable('Invalid password.', errorData))
}
//creates new mongo user
const UserData = new User(user)
//sets user password hash
UserData.setPassword(password)
return UserData;
}
Run Code Online (Sandbox Code Playgroud)
请注意:存根和模拟通常是一种代码味道:可能有更好的测试方法,或者它可能表明需要将代码重构为更容易测试的东西。它们通常指向紧密耦合或混乱的代码。
查看有关该主题的这篇精彩文章:https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |