AngularJS茉莉花工厂与间谍进行测试

时间:2015-05-29 09:26:44

标签: angularjs jasmine

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

在测试中,我想检查是否调用了新的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时,我收到了错误。

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

1 个答案:

答案 0 :(得分: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/