我正在使用经过验证的方法 (mdg:validated-method
) 和 LoggedInMixin (tunifight:loggedin-mixin
)。
现在我的单元测试出现了问题,因为它们因 notLogged
错误而失败,因为在单元测试中当然没有登录用户。
我怎么必须 stub 呢?
方法
const resetEdit = new ValidatedMethod({
name: 'reset',
mixins: [LoggedInMixin],
checkLoggedInError: { error: 'notLogged' }, // <- throws error if user is not logged in
validate: null,
run ({ id }) {
// ...
}
})
单元测试
describe('resetEdit', () => {
it('should reset data', (done) => {
resetEdit.call({ id: 'IDString' })
})
})
单元测试抛出 错误:[notLogged]
。
最佳答案
编辑:
validated-method
有一种提供上下文的内置方式,它记录在 README
中,完全适用于您问题中的情况。
method#_execute(context: Object, args: Object)
Call this from your test code to simulate calling a method on behalf of a particular user:
(source)
it('should reset data', (done) => {
resetEdit._execute({userId: '123'}, { id: 'IDString' });
done();
});
原答案:
我相信这可以使用 DDP._CurrentMethodInvocation
meteor 环境变量来实现。
如果您在其值是对象 userId
字符串的范围内运行测试,它将与方法调用上下文对象的其余部分合并,混合将不会失败。
describe('resetEdit', () => {
it('should reset data', (done) => {
DDP._CurrentMethodInvocation.withValue({userId: '123'}, function() {
console.log(DDP._CurrentInvocation.get()); // {userId: '123'}
resetEdit.call({ id: 'IDString' });
done();
})
});
})
关于javascript - meteor JS : How to stub validated method in unit test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46479562/