2014-09-23 70 views
1

嘿我想單元測試一個方法,但我得到一個錯誤「錯誤:createUser()方法不存在」當我spyOn Accounts.createUser,但是當我spyOn Meteor.user,我沒有任何問題,這是我到目前爲止。單元測試註冊用戶方法與流星茉莉

服務器/方法/ user.js的

Meteor.methods({ 
    'registerUser' : function (options) { 

     if(Meteor.user()) 
     throw new Meteor.Error(403, "Account has already been registered, log out to create a new account"); 

     if(options.password.length < 8) 
     throw new Meteor.Error(403, "Password must have at least 8 characters"); 

     var id = Accounts.createUser(options); 
     if(options.type === "b") Roles.addUsersToRoles(id, 'user-b'); 
     else Roles.addUsersToRoles(id, 'user-c'); 

     return 0; 
    } 
}); 

Accounts.validateNewUser(function (user) { 
    if (user.emails[0].address && user.emails[0].address.length >= 5) 
    return true; 
    throw new Meteor.Error(403, "Invalid email address"); 
}); 

Accounts.onCreateUser(function(options, user) { 
    if(options.type === "b"){ 
     var key = RegKey.findOne({ key: options.key, valid: true }); 
     if(key) RegKey.update({ _id: key._id },{ valid: false }); 
     else throw new Meteor.Error(403, "Invalid Code"); 
    } 
    return user; 
}); 

測試/茉莉/服務器/單元/ user.js的

"use strict"; 
describe("User", function() { 

    it("should be able to register with valid email and password", function() { 
    spyOn(Accounts, "createUser").and.returnValue("id"); 

    Meteor.methodMap.registerUser({ 
     email: "[email protected]", 
     password: "abcd1234" 
    }); 

    expect(Accounts.createUser).toHaveBeenCalledWith({ 
     email: "[email protected]", 
     password: "abcd1234" 
    }); 
    }); 
}); 

回答

1

測試茉莉單元測試運行流星上下文之外。這意味着你的測試代碼是快速的,孤立的,只測試你想要的東西。但是,您的應用程序中預計Meteor將在那裏的代碼將無法正常運行。

茉莉花定勢是通過建立「存根」

beforeEach(function() { 
    MeteorStubs.install(); 
}); 

afterEach(function() { 
    MeteorStubs.uninstall(); 
}); 

這是服務器單元測試自動完成。如果要編寫在瀏覽器中運行的單元測試,則需要自己爲客戶端測試執行此操作。

如果我們看一下它們例如模擬服務https://github.com/alanning/meteor-stubs/blob/master/index.js 我們可以看到, '的createUser()' 缺少

stubFactories.Accounts = function() { 
var Meteor = stubFactories.Meteor(); 

return { 
    emailTemplates: { enrollAccount: emptyFn }, 
    config: emptyFn, 
    urls: {}, 
    registerLoginHandler: emptyFn, 
    onCreateUser: emptyFn, 
    loginServiceConfiguration: new Meteor.Collection('loginserviceconfiguration'), 
    validateNewUser: emptyFn 
}; 

};

不像Meteor.user是定義。 https://github.com/alanning/meteor-stubs/blob/master/index.js#L264