我想用mocha,sinon和chai测试我的角度应用程序.
特别是我对提交功能很感兴趣.如何为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
});
最佳答案 如果要模拟服务,可以在设置模拟值时创建测试模块:
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');
});