【问题标题】:angular testing with sinon, mocha, chai使用 sinon、mocha、chai 进行角度测试
【发布时间】:2023-03-22 17:31:01
【问题描述】:

我想用 mocha、sinon 和 chai 测试我的 Angular 应用程序。 特别是我对提交功能感兴趣。如何为 LoginResoure 创建 mock 或 stub 以测试此功能。

谢谢!

(function () {
'use strict';

class LoginController {
    constructor($state,LoginResource) {
        this.resource = LoginResource;
        this.$state = $state;
        this.credentials = {};
    }
    submit() {
      let promise = this.resource.login(this.credentials);
       promise.then(()=>{
           changeState()
      }
    }
    changeState() {
         this.$state.go('home');
    }
}


angular.module('app.login').controller('LoginController', LoginController);
})();



    (function () {
'use strict';

class LoginResource {
    constructor($resource, API_LOGIN) {
        this.$resource = $resource(API_LOGIN,{'@id':id})
    }

    login(data) {
        return this.$resource.save(data).$promise;
    }
}

angular.module('app.login').service('LoginResource', LoginResource);
})();

编辑: 以前我用茉莉花做下一种方式:

            let deferred = $q.defer();
            deferred.resolve('Remote call result');
            mockPeopleResource = {
                createPerson: jasmine.createSpy('createPerson').and.returnValue(deferred.promise)
            };

或者如果我想模拟@resource

    mockThen = jasmine.createSpy();
    mockGetPeoplePromise = {then: mockThen};
    mockUpdate = jasmine.createSpy().and.returnValue({$promise: mockPromise});
    mockSave = jasmine.createSpy().and.returnValue({$promise: mockPromise});
    mockGetPeopleQuery = jasmine.createSpy().and.returnValue({$promise: mockGetPeoplePromise});
    mockResource = jasmine.createSpy().and.returnValue({
        get: mockGet,
        update: mockUpdate,
        save: mockSave,
        query: mockGetPeopleQuery
    });

【问题讨论】:

    标签: angularjs mocha.js sinon sinon-chai


    【解决方案1】:

    如果你想模拟一个服务,你可以在设置模拟值时创建一个测试模块:

    beforeEach(function() {
      angular.module('test', []).factory('LoginResource', function($q) {
        return {
          /* You can mock an easy login function that succeed when
             data >= 0 and fails when data < 0  */
          login: function(data) {
            return $q(function(resolve, reject) {
              if (data >= 0) return resolve();
              reject();
            });
          }
        };
      });
    
      module('app.login', 'test');
    });
    

    【讨论】:

    • 太复杂了。有了茉莉花,我做起来就简单多了。查看编辑
    猜你喜欢
    • 2015-10-01
    • 2016-05-26
    • 2021-09-27
    • 2015-12-01
    • 2018-04-08
    • 2019-02-14
    • 2023-04-11
    • 2017-10-08
    • 2019-02-03
    相关资源
    最近更新 更多