1

我有一个经过验证的方法,我正在为其编写测试。该方法检查用户是否是管理员,如果不是则抛出错误。

我正在使用 dburles:factory 在 Meteor.users 集合中创建一个具有“管理员”角色的新用户。

然后,我使用“管理员”用户的 userId 调用经过验证的方法,但它会引发错误。

尽管我根据文档使用管理员用户的上下文调用该方法,但它似乎没有将其传递给该方法。当我console.log(this.userId);在方法中它返回未定义。

谁能检查我的代码并告诉我为什么会这样?谢谢!

方法代码:

import { Meteor } from 'meteor/meteor';
import { Clients } from '../../clients';
import SimpleSchema from 'simpl-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { Roles } from 'meteor/alanning:roles';

export const createClient = new ValidatedMethod({
    name: 'Clients.methods.create',
    validate: new SimpleSchema({
        name: { type: String },
        description: { type: String },
    }).validator(),
    run(client) {

        console.log(this.userId); //this is undefined for some reason

        if(!Roles.userIsInRole(this.userId, 'administrator')) {
            throw new Meteor.Error('unauthorised', 'You cannot do this.');
        }
        Clients.insert(client);
    },
});

测试代码:

import { Meteor } from 'meteor/meteor';
import { expect, be } from 'meteor/practicalmeteor:chai';
import { describe, it, before, after } from 'meteor/practicalmeteor:mocha';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { sinon } from 'meteor/practicalmeteor:sinon';
import { Factory } from 'meteor/dburles:factory';

import { createClient } from './create-client';
import { Clients } from '/imports/api/clients/clients';

describe('Client API Methods', function() {
  afterEach(function() {
    resetDatabase();
  });

  it('Admin user can create a new client', function() {
    let clientName = "Test",
        description = "This is a description of the client!",
        data = {
          name: clientName,
          description: description
        };

    Factory.define('adminUser', Meteor.users, {
      email: 'admin@admin.com',
      profile: { name: 'admin' },
      roles: [ 'administrator' ]
    });

    const admin = Factory.create('adminUser');

    console.log(Roles.userIsInRole(admin._id, 'administrator'));// this returns true

    //invoking the validated method with the context of the admin user as per the documentation
    createClient._execute(admin._id, data);

    let client = Clients.findOne();


    expect(Clients.find().count()).to.equal(1);
    expect(client.name).to.equal(clientName);
    expect(client.description).to.equal(description);
  });
4

1 回答 1

1

我已经为我的问题制定了解决方案。

当您执行经过验证的方法时,您需要将 userId 作为对象传递,例如{ userId: j8H12k9l98UjL }

我将它作为字符串传递,因此不会使用 Factory 创建的用户上下文调用该方法。

该测试现在完美运行

希望这对其他人有帮助

于 2017-01-08T23:17:58.647 回答