【问题标题】:AngularJS jasmine factory tests with spyAngularJS 茉莉花工厂测试与间谍
【发布时间】:2015-05-29 09:26:44
【问题描述】:

我有一个帐户和用户工厂。现在我想测试帐户工厂。

在测试中我想检查是否调用了 new User() 并返回了假数据。

angular.module('app')

.factory 'Account', [ 'User', (User) ->
  class @Account
    constructor: (account) ->
      @self = this
      @user = new User(account.user_id)
]

.factory 'User', [ '$http', ($http) ->
  class @User
    constructor: (id)
      $http.get('/user.json?id='+id)
      .success (data) =>
        //do something
      .error (data) ->
        //do something
]

测试:

describe 'app', ->
  describe 'Account', ->
    Account   = undefined
    User      = undefined

    beforeEach(module('app'))

    beforeEach inject((_Account_, _User_) ->
      Account = _Account_
      User    = _User_
    )

    describe 'initialize', ->
      it 'should call new User', ->
        spyOn(window, 'User').and.callFake( (value) ->
          return value
        )
        account = new Account({ id: 1 })

我总是: 错误:User() 方法不存在

这里是fiddle

当我删除间谍时,测试是绿色的,并且调用了 console.log。 当我添加 spyOn 时,我得到了错误。

如何进行测试以检查是否调用了新用户?

【问题讨论】:

  • 您要求 Jasmine 监视 window 对象的 User 方法:spyOn(window, 'User')
  • 我不知道有其他方法可以监视新用户,但窗口不知道用户。
  • 创建Account时,需要发送一个mock User
  • 对不起,我不知道该怎么做
  • 您必须使用$provide 来创建您的工厂。 stackoverflow.com/questions/14773269/…

标签: angularjs jasmine


【解决方案1】:

模拟一个Angular服务的方式(在JS中,我不会说CS):

describe('app', function() {
    describe('Account', function() {

        var Account, User;

        // This is always first
        beforeEach(module('app'));

        // This ***HAS*** to go before the beforeEach(inject(...)) block
        beforeEach(function() {
            User = ...; // mock it as necessary, e.g. jasmine.createSpy('UserMock')

            module(function($provide) {
                $provide.value('User', User);
            });
        });

        beforeEach(inject(function(_Account_) {
            Account = _Account_;
        }));

        // Now the User is mocked
        ...
    });
});

如果Userjasmine.createSpy 模拟,那么下面的小提琴演示了一个成功的测试:http://jsfiddle.net/7Lveyb50/

【讨论】:

  • 谢谢,但是如何检查用户是否被调用?
  • 这取决于你打算如何模拟它。
  • 感谢小提琴。对我来说还有一个问题。我如何在这个使用 createSpy 创建的间谍上调用 .callFake。
猜你喜欢
  • 1970-01-01
  • 2014-03-18
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
相关资源
最近更新 更多