Luc*_*cas 4 javascript unit-testing angularjs
所以我是 angularjs 及其模拟库的新手。我正在尝试测试是否发出了特定的 GET 请求,但是对于第二个断言,我总是收到此错误并且无法弄清楚原因:
Error: Unsatisfied requests: GET /1.json
Run Code Online (Sandbox Code Playgroud)
我在下面的代码中有什么问题吗?
应用程序.js
var App = angular.module('App', []).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
}).when('/Items', {
templateUrl: 'views/items.html',
controller: 'Ctrl'
}).otherwise({
redirectTo: '/'
});
}]);
Run Code Online (Sandbox Code Playgroud)
控件.js
function Ctrl($scope, $http, $filter) {
$scope.items = [];
$http.get('/1.json').success(function(data) {$scope.items = data.items;});
}
Ctrl.$inject = ["$scope","$http", "$filter"];
Run Code Online (Sandbox Code Playgroud)
规范/Ctrl.js
describe('Controller: Ctrl', function() {
var $httpBackend;
// load the controller's module
beforeEach(module('App'));
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
$httpBackend.whenGET('/1.json').respond('Response!');
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
var Ctrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
Ctrl = $controller('Ctrl', {
$scope: scope
});
}));
it('should initialize with 0 items', function() {
expect(scope.items.length).toBe(0);
$httpBackend.flush();
});
it('should make store request', function(){
var controller = scope.$new(Ctrl);
$httpBackend.expectGET('/1.json');
$httpBackend.flush();
});
});
Run Code Online (Sandbox Code Playgroud)
编辑:添加了应用程序和控制器代码。
我终于让我的单元测试工作了!主要是因为我重新构建了我的应用程序,使其更有意义并且更模块化。
我将尝试提供信息以帮助下一个遇到此问题的人:
首先是我改用 $resource 而不是 $http。
我没有注入 $injector,而是像这样注入了$httpBackend:
beforeEach(inject(function(_$httpBackend_, $rootScope, $route, $controller){
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/path/to/api').respond([{id:1}]);
Run Code Online (Sandbox Code Playgroud)
我没有将 'Ctrl' 作为字符串引用,而是传入了实际的类
Ctrl = $controller('Ctrl', {
$scope: scope
});
变成了
var ProductsCtrl = ['$scope', function($scope){ ... }];
Ctrl = $controller(ProductsCtrl, {
$scope: scope
});`
Run Code Online (Sandbox Code Playgroud)
如果您使用 $resources,请确保您正在引用 angular-resources.js 文件
我真的很喜欢 Angularjs;我认为只需要一些时间来了解如何进行测试。祝你好运!
| 归档时间: |
|
| 查看次数: |
8194 次 |
| 最近记录: |