2015-05-01 57 views
0

我试图编写一个unit test用于在ajax调用中使用simple-auth authentication的控制器。断言测试效果很好,但session属性似乎没有在unit test模块范围中定义。使用ember-cli-simple-auth进行Ember-cli单元测试

实施例动作在控制器:

authenticate() { 
    let credentials = this.getProperties('identification', 'password'); 
    this.get('session').authenticate('simple-auth-authenticator:token', credentials) 
    .then(() => { 
     this.transitionToRoute('index'); 
    }, (error) => { 
     this.set('errorMessage', error.error); 
    }); 
} 

实施例试验:

it('should not authenticate', function() { 
    let controller = this.subject(); 
    controller.send('authenticate'); 
    expect(controller.get('errorMessage')).to.equal("Invalid email/password combination"); 
}); 

会话是未定义的错误消息:

TypeError: Cannot read property 'authenticate' of undefined 
at authenticate (http://localhost:7357/assets/app.js:587:28) 
at mixin.Mixin.create.send (http://localhost:7357/assets/vendor.js:37164:54) 
at Context.<anonymous> (http://localhost:7357/assets/app.js:2002:18) 
at Context.wrapper (http://localhost:7357/assets/test-support.js:1756:27) 
at invoke (http://localhost:7357/assets/test-support.js:13772:21) 
at Context.suite.on.context.it.context.specify.method (http://localhost:7357/assets/test-support.js:13837:13) 
at Test.require.register.Runnable.run (http://localhost:7357/assets/test-support.js:7064:15) 
at Runner.require.register.Runner.runTest (http://localhost:7357/assets/test-support.js:7493:10) 
at http://localhost:7357/assets/test-support.js:7571:12 
at next (http://localhost:7357/assets/test-support.js:7418:14) 

回答

1

在单元测试你没有一个运行的应用程序所以在初始化器中发生的注射等不会运行。确保会话存在于控制器中的最好方法是将其存根,这也可以很容易地确保它在您的测试中的行为。

另一种方法是将单元测试转变为验收测试 - 在这种情况下,您有一个初始化的应用程序,测试运行并且会话将在控制器中可用。