MeteorJS:如何在单元测试中存根验证方法
MeteorJS: How to stub validated method in unit test
我正在使用经过验证的方法 (mdg:validated-method
) 和 LoggedInMixin (tunifight:loggedin-mixin
)。
现在我的单元测试有问题,因为它们失败并出现 notLogged
错误,因为在单元测试中当然没有登录用户。
我怎么必须存根呢?
方法
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' })
})
})
单元测试抛出 Error: [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
字符串的范围内进行测试,它将与方法调用上下文对象的其余部分合并,mixin 不会失败。
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();
})
});
})
我正在使用经过验证的方法 (mdg:validated-method
) 和 LoggedInMixin (tunifight:loggedin-mixin
)。
现在我的单元测试有问题,因为它们失败并出现 notLogged
错误,因为在单元测试中当然没有登录用户。
我怎么必须存根呢?
方法
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' })
})
})
单元测试抛出 Error: [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
字符串的范围内进行测试,它将与方法调用上下文对象的其余部分合并,mixin 不会失败。
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();
})
});
})