0
我有一個驗證的方法,我正在爲其編寫測試。該方法檢查用戶是否是管理員,如果不是,則會拋出錯誤。測試時將Meteor.userId傳遞給驗證的方法
我正在使用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: '[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);
});