Angularjs服务单元测试
Angularjs Unit Test for Service
我正在消费一个服务,我正在为它编写单元测试用例。当注入service
&从controller
调用函数,我没有得到data
。我刚开始写案例。
这是我的代码。
StatesList服务angular.module('myApp').factory('StatesList', ['$resource', function($resource) {
return $resource('/api/states');
}]);
控制器$scope.statesList = function () {
StatesList.query(function (states) {
// Brings all states
$scope.states = states;
});
};
测试describe('States List', function () {
var ctrl, scope, statesService;
beforeEach(function () {
module('myApp');
inject(function ($rootScope, $controller, StatesList) {
scope = $rootScope.$new();
statesService = StatesList;
ctrl = $controller('StatesCtrl', { $scope: scope, StatesList: statesService });
});
});
it('should have practice list to be null', function () {
console.log('List of States');
scope.statesList();
console.log(scope.states); // I don't see any data here
expect(scope.states).not.toBeNull();
});
WebStorm的输出
'List of States'
undefined
为什么状态不显示。通过使用POSTMAN可以看到数据
StatesList.query()
是一个异步http调用,因此您需要在测试中使用ngMock
模块中的模拟$httpBackend
服务。将angular-mock.js
添加到您的测试配置中,然后尝试:
describe('States List', function () {
var ctrl, scope, statesService, $httpBackend;
beforeEach(function () {
module('myApp');
inject(function ($rootScope, $controller, StatesList, _$httpBackend_) {
scope = $rootScope.$new();
statesService = StatesList;
ctrl = $controller('StatesCtrl', { $scope: scope, StatesList: statesService});
$httpBackend = _$httpBackend_;
});
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should have practice list to be null', function () {
$httpBackend.expectGET('/api/states').respond([{ // ask mock $httpBackend to respond with fake data
name: 'State 1'
}, {
name: 'State 2'
}]);
console.log('List of States');
scope.statesList();
$httpBackend.flush(); // flush the http request to send fake data back to StatesList.query()
console.log(scope.states); // I don't see any data here
expect(scope.states).not.toBeNull();
});
});
相关文章:
- Jasmine单元测试在监视服务方法时失败
- Angular 2和服务单元测试
- 在http服务单元测试中使用request-js时,chai.request不是一个函数
- $cacheFactory removeAll() 在服务中的单元测试在 Angular 1.2.0 中失败,但在 1.
- 如何在 angularjs 茉莉花单元测试中正确引用服务
- 无法将服务注入其 Angular 单元测试中
- 角度单元测试服务元素持久性
- 在 Karma/Jasmine 单元测试中注入 Angular $timeout服务的真实实现
- 尝试在 AngularJS 上对基本服务进行单元测试时出错
- 单元测试依赖于服务的角度过滤器
- 类型错误:parsed 在 angularjs 服务单元测试中未定义
- 如何在Jasmine中对依赖服务的函数进行单元测试
- 单元测试服务不;t注入工厂
- 为创建Json REST服务的模块编写单元测试
- 如何对一个主要负责重定向到应用程序外部页面的Angular服务进行单元测试
- 错误:单元测试AngularJs服务时,没有待处理的flush请求
- 单元测试调用服务的指令
- Angular.js承诺在单元测试服务时不解决因果报应问题
- Angularjs单元测试服务承诺
- AngularJS与Jasmine、Karma和ng Mock的单元测试服务