5
我正在爲流星寫單元測試的噩夢。有太多陳舊過時的文章和太少的清晰相關的文檔讓我能夠弄清楚爲了實現這個目標我需要做些什麼。如何用流體單元測試流星法:摩卡
我遇到了問題後的問題,只是真的希望有人能告訴我他們將如何爲我的一種方法編寫測試,以便我可以看到他們已經完成了什麼,並對其餘的方法進行反向工程。
這是我想編寫一個測試方法:
Meteor.methods({
'client.new':(clientDetails) => {
check(clientDetails, {
name: String,
numberTeamMembers: String
});
clientDetails.teamMembers = [];
if(!Meteor.userId() || !Roles.userIsInRole(Meteor.userId(), 'administrator')) {
throw new Meteor.Error('500', 'You are not authorised to do this.');
}
if(Clients.findOne({ name: clientDetails.name})) {
throw new Meteor.Error('500', 'This client name already exists!');
};
return Clients.insert(clientDetails);
},
});
到目前爲止,我有以下:
import { Meteor } from 'meteor/meteor';
import { expect, be } from 'meteor/practicalmeteor:chai';
import { describe, it, before } from 'meteor/practicalmeteor:mocha';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { Random } from 'meteor/random';
import { Clients } from '/imports/api/clients/clients.js';
import '/imports/api/clients/server/methods.js';
describe('Client Methods in API', function() {
before(function() {
resetDatabase();
});
it('can create a Client', function(){
let clientName = "Microsoft",
numberTeamMembers = "5",
data = {
name: clientName,
numberTeamMembers: numberTeamMembers
};
let userId = Accounts.createUser({username: "admin", email: "[email protected]", password: "password"});
Meteor.users.update({ _id: userId }, { $set: { roles: [ 'administrator' ] }});
let method = Meteor.server.method_handlers['client.new'];
method.apply(userId, [data]);
let client = Clients.findOne();
expect(Clients.find().count()).to.equal(1);
expect(client.name).to.equal(clientName);
expect(client.numberTeamMembers).to.equal(numberTeamMembers);
});
});
上面的測試拋出的錯誤是,首先它告訴我Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
這是不相關的,因爲這是我測試的一種方法。其次,該方法會拋出錯誤('您無權執行此操作'),因此無法識別Meteor.userId()或用戶處於'管理員'角色的事實。
如果有人能告訴我他們將如何測試該方法,我會非常感激!
感謝
用戶需要先登錄在調用方法之前。即使我也遇到了同樣的問題。讓我知道你是否發現任何東西。 –