我想用 mocha、sinon 和 chai 测试我的 Angular 应用程序。特别是我对提交功能感兴趣。如何为 LoginResoure 创建模拟或存根以测试此功能。
谢谢!
(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
});