У меня есть проверенный метод, для которого я пишу тест. Метод проверяет, что пользователь является администратором, и выдает ошибку, если это не так.Передача Meteor.userИдентифицированный метод при тестировании
Я использую dburles: factory, чтобы создать нового пользователя с ролью администратора в коллекции Meteor.users.
Затем я вызываю проверенный метод, используя userId пользователя 'admin', но он выдает ошибку.
Хотя я вызываю метод, используя контекст пользователя-администратора в соответствии с документацией, он, похоже, не передает его методу. Когда I 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: '[email protected]',
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);
});