在测试

时间:2017-01-08 22:04:39

标签: javascript unit-testing meteor mocha meteor-methods

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

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

然后我使用'admin'用户的userId调用经过验证的方法,但是它抛出了一个错误。

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

任何人都可以检查我的代码并告诉我为什么会这样吗?谢谢!

方法代码:

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);
  });

1 个答案:

答案 0 :(得分:1)

我已经解决了我的问题。

执行经过验证的方法时,需要将userId作为{ userId: j8H12k9l98UjL }

等对象传递

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

此测试现在完美无缺

希望这有助于其他人

相关问题