我正在尝试为使用 $http 服务获取文章详细信息的控制器编写单元测试。
控制器:
.controller('ArticleDetailCtrl',function($scope, Article, $routeParams, API_URL, ARTICLE_URL, $http, $sce){
$scope.url = API_URL + ARTICLE_URL + '/' + $routeParams.articleId;
$http.get($scope.url).then(function(response) {
//console.log(response.data);
$scope.heading = response.data.Headline;
$scope.rawBody = response.data.Body;
$scope.body = $sce.trustAsHtml($scope.rawBody);
$scope.image = response.data.Assets[0].URL;
});
});
单元测试:
'use strict';
describe('Controller: Article', function () {
var scope,
$httpBackend,
articleEndpoint;
// load the controller's module
beforeEach(module('myApp'));
describe('ArticleDetailCtrl', function () {
var ArticleDetailCtrl,
jsonObject,
ArticleId = '123';
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, _$httpBackend_, Article, API_URL, ARTICLE_URL) {
scope = $rootScope.$new();
ArticleDetailCtrl = $controller('ArticleDetailCtrl', { $scope: scope });
$httpBackend = _$httpBackend_;
articleEndpoint = API_URL + ARTICLE_URL + '/' + ArticleId;
jsonObject = {
'Headline': 'Headline',
'Body': '<p>Body</p>',
'Assets': [
{
'URL': 'path/to/image/article1.jpg'
}
]
};
$httpBackend.when('GET', articleEndpoint).respond(jsonObject);
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch article details from the API', function () {
//expect(scope.articles.length).toEqual(3);
$httpBackend.expectGET(articleEndpoint);
$httpBackend.flush();
});
});
});
但我不断收到以下错误:
Error: Unexpected request: GET http://localhost:3000/api/articles/undefined
Expected GET http://localhost:3000/api/articles/123
at $httpBackend (/Users/gill/Documents/projects/angularjs-test/app/bower_components/angular-mocks/angular-mocks.js:1179)
at sendReq (/Users/gill/Documents/projects/angularjs-test/app/bower_components/angular/angular.js:8181)
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular/angular.js:7921
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular/angular.js:11319
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular/angular.js:11405
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular/angular.js:12412
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular/angular.js:12224
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular-mocks/angular-mocks.js:1438
at /Users/gill/Documents/projects/angularjs-test/test/spec/controllers/article.js:77
Error: Unsatisfied requests: GET http://localhost:3000/api/articles/123
at /Users/gill/Documents/projects/angularjs-test/app/bower_components/angular-mocks/angular-mocks.js:1472
at /Users/gill/Documents/projects/angularjs-test/test/spec/controllers/article.js:65
这是我第一次编写单元测试,随后我阅读了一些教程。我不知道我做错了什么?