我正在针对我的js
控制器编写单元测试,该控制器通过资源启动http
调用 - >服务。我需要模拟http调用并进入response.then
initialCompetitions
方法(从未发生过)
controller.js
class Controller {
constructor(
this.competitions = [];
)
$onInit() {
this.initialCompetitions();
}
initialCompetitions = function() {
let response = this.service.allCompetitions();
var vm = this;
response.then(function(value) {
vm.competitions = value.data;
});
};
}
export default Controller;
service.js
class Service {
allCompetitions = function () {
return this.competitionResource.all();
};
}
export default Service;
competitionResource.js
class CompetitionResource {
constructor($http, $q) {
this.$http = $http;
this.apiUrlAll = 'path to api';
this.$q = $q;
}
all = function() {
var defer = this.$q.defer();
this.$http({
url: this.apiUrlAll,
method: 'GET'
})
.then(function(response) {
defer.resolve(response);
},
function(response) {
defer.reject(response);
});
return defer.promise;
}
}
export default CompetitionResource;
单元测试规范文件:
describe('unit test', () => {
let $rootScope, $location, $scope, $compile, controller, $q, mockData, service;
mockData = {
// data to mock
};
beforeEach(inject(($injector) => {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
$location = $injector.get('$location');
$compile = $injector.get('$compile');
$q = $injector.get('$q');
}));
beforeEach(() => {
service = {
allCompetitions: function() {
var deferred = $q.defer();
deferred.resolve(mockCompetitionsData);
return deferred.promise;
}
};
controller = new Controller();
});
describe('initialCompetitions()', () => {
it('should populate competitions', () => {
expect(controller.competitions).to.be.empty;
controller.initialCompetitions();
expect(controller.competitions).to.not.be.empty; // fails because competitions are still empty
});
});
});
expect(controller.competitions).to.not.be.empty;
失败,因为competitions
仍然是一个空数组[]
我怀疑我需要以某种不同的方式嘲笑承诺,但无法弄清楚如何。