我正在为流星做噩梦写作单元测试。有太多旧的,过时的文章和太少的清晰,相关的文档,以便我能够找出实际需要做的事情来实现这一点。
我在遇到问题之后遇到了问题,并且真的希望有人能告诉我他们如何为我的一种方法编写测试,这样我就可以看到他们做了什么,并为我的其余部分进行逆向工程方法。
这是我想为以下方法编写测试的方法:
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: "admin@admin.com", 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()或用户在&#39中的事实;管理员'作用。
如果有人能告诉我他们将如何测试这种方法,我真的很感激它!
由于
答案 0 :(得分:3)
我认为你需要研究Meteor.user()
方法,试试这个:
import { Meteor } from 'meteor/meteor';
import { resetDatabase } from 'meteor/xolvio:cleaner';
import { sinon } from 'meteor/practicalmeteor:sinon';
describe('...', () => {
let currentUser;
beforeEach(() => {
resetDatabase();
Factory.define('user', Meteor.users, {
profile: {
// ...
},
});
currentUser = Factory.create('user');
sinon.stub(Meteor, 'user');
Meteor.user.returns(currentUser);
});
afterEach(() => {
Meteor.user.restore();
resetDatabase();
});
it('...', () => {
// ...
});
});
您需要添加以下软件包:dburles:factory
,xolvio:cleaner
,practicalmeteor:sinon