[英]How to test Meteor.users with Mocha
我有如下功能:
if(Meteor.isServer) {
Meteor.methods({
addUser: function (newUser) {
check(newUser, { email: String, password: String });
userId = Accounts.createUser(newUser);
return userId;
},
getUser: function (userID) {
check(userID, String);
return Meteor.users.find({_id: userID}).fetch();
}
});
我正在尝试使用Mocha测试此功能:
if (Meteor.isServer) {
let testUser;
describe('Users', () => {
it("Add User", (done) => {
testUser = {email: 'test@test.test', password: 'test'};
try {
testUser._id = Meteor.call('addUser', testUser);
console.log(Accounts.users.find({_id: testUser._id}).fetch());
done();
} catch (err) {
assert.fail();
}
});
it("Get user", (done) => {
try {
Meteor.call('getUser', testUser._id);
done();
} catch (err) {
assert.fail();
}
});
});
而且我知道使用'addUser'进行流星调用是有效的,因为之后的console.log会返回我刚刚制作的用户,当我使用“meteor test --driver-package practicalmeteor:mocha”运行它时,第一次测试通过
但后来我来到第二个测试部分,在那里我尝试让用户使用流星调用'getUser',但后来我卡住了:
'无法调用方法'找到'未定义'
现在我知道不同之处在于我使用'Meteor.users'而不是'Account.users'来找到用户,但我完全处于黑暗中,这两者之间的区别是什么。 我应该用Accounts.user方法调用替换所有Meteor.users方法调用吗? 你会怎么测试这个?
我只是偶然发现了这篇文章,因为我几个小时前处理过同样的问题。
正如我在您的代码中看到的那样,您的testUser在您的第一个单元中定义( it("Add User"...){}
)。 我建议你不要使用第二个单元中第一个单元的值。
您可能更喜欢使用beforeEach和afterEach为每个单元进行干净设置,然后在第二个测试单元中创建一个新用户。 您还应该在每个单元后清理数据库:
describe('Users', () => {
// use this for each test
let testUser;
beforeEach(() => {
// let's always create a new clean testUser object
testUser = {email: 'test@test.test', password: 'test'};
});
afterEach(() => {
// Remove the user to keep our db clean
if (testUser._id)
Meteor.users.remove(testUser._id);
});
it("Add User", (done) => {
testUser._id = Meteor.call('addUser', testUser);
const users = Meteor.users.find({_id: testUser._id}).fetch();
const user = users[0];
assert.isNotNull(user);
assert.isDefined(user);
assert.equal(user._id, testUser._id);
done();
});
it("Get user", (done) => {
// get a new id from our previously tested
// (and assume to be working) function
testUser._id = Meteor.call('addUser', testUser);
const user = Meteor.call('getUser', testUser._id);
assert.isNotNull(user);
assert.isDefined(user);
assert.equal(user._id, testUser._id);
done();
});
});
我还发现,你的'getUser'方法返回一个数组,所以我将它改为:
getUser: function (userID) {
check(userID, String);
const users = Meteor.users.find({_id: userID}).fetch();
return users[0];
}
全部测试并运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.