【问题标题】:"Meteor.userId can only be invoked in method calls" in Meteor Method testMeteor Method 测试中的“Meteor.userId 只能在方法调用中调用”
【发布时间】: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 &amp;&amp; task.owner !== Meteor.userId()) {... IMO,此更改使测试到达失败的表达式,因为使用原始代码测试通过了。

我还提到将Meteor.userId() 更改为this.userId 可以使测试通过,并且应用程序看起来也可以像以前一样工作。

所以,我的问题基本上是:为什么错误消息显示有争议的 (IMO) 信息以及在方法中使用 this.userIdMeteor.userId() 有什么区别?

我的完整“Todo 教程”项目代码可以在以下位置找到:https://github.com/kemsbe/simple-todo

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    基本上 this.userId 使用函数的this 上下文,而 Meteor.userId() 使用当前的 Fiber 来获取 userId。

    如果您希望您的代码与 Meteor.userId() 一起使用,您需要在光纤中运行您的函数。你可以做的另一件事是存根meteor.userId,就像How to unit test a meteor method with practicalmeteor:mocha中解释的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多