【发布时间】:2017-05-09 22:14:33
【问题描述】:
我正在按照官方网站上的基本“Todo 教程”学习 Meteor。我对“测试”步骤有疑问。 我对一种方法进行了基本测试,它看起来像这样:
if (Meteor.isServer) {
describe('Tasks', () => {
describe('methods', () => {
const userId = Random.id();
let taskId;
beforeEach(() => {
Tasks.remove({});
taskId = Tasks.insert({
text: 'test task',
createdAt: new Date(),
owner: userId,
username: 'tmeasday',
});
});
it('can delete owned task', () => {
const deleteTask = Meteor.server.method_handlers['tasks.remove'];
const invocation = { userId };
deleteTask.apply(invocation, [taskId]);
assert.equal(Tasks.find().count(), 0);
});
});
});
}
此测试失败并出现错误:
Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
at AccountsServer.userId (packages/accounts-base/accounts_server.js:82:13)
at Object.Meteor.userId (packages/accounts-base/accounts_common.js:257:19)
at Object.Meteor.methods.tasks.remove (imports/api/tasks.js:37:35)
at Test.<anonymous> (imports/api/tasks.tests.js:27:28)
at run (packages/practicalmeteor:mocha-core/server.js:34:29)
at Context.wrappedFunction (packages/practicalmeteor:mocha-core/server.js:63:33)
IMO,这个错误信息是有争议的,因为它说的是我没有犯的错误,因为从错误信息的第 4 行我可以看到,stacktrace 指向方法声明体,这个:
'tasks.remove' (taskId) {
check(taskId, String);
const task = Tasks.findOne(taskId);
if (task.owner !== Meteor.userId()) { // <- ERROR MESSAGE POINTS TO THIS LINE
// If the task is private, make sure only the owner can delete it
throw new Meteor.Error('not-authorized');
}
Tasks.remove(taskId);
},
教程代码和我的代码有 1 个区别:我从 if 语句中删除了条件 !todo.private,所以在原始教程中它们看起来像这样:
if (!task.private && task.owner !== Meteor.userId()) {...
IMO,此更改使测试到达失败的表达式,因为使用原始代码测试通过了。
我还提到将Meteor.userId() 更改为this.userId 可以使测试通过,并且应用程序看起来也可以像以前一样工作。
所以,我的问题基本上是:为什么错误消息显示有争议的 (IMO) 信息以及在方法中使用 this.userId 和 Meteor.userId() 有什么区别?
我的完整“Todo 教程”项目代码可以在以下位置找到:https://github.com/kemsbe/simple-todo
【问题讨论】:
标签: javascript meteor