gpt4 book ai didi

angularjs - 使用 $window.location.pathname 对 angularjs 进行单元测试

转载 作者:行者123 更新时间:2023-12-03 08:08:59 28 4
gpt4 key购买 nike

我有一个像这样的 angularjs Controller :

myApp.controller('SetCourseCtrl', function($scope, $http, $window,$sce) {
var path = $window.location.pathname;
path = path.split('/');
var courseID = path.pop();
$http.post('/course/getCourse', {
courseID: courseID
}).then(function(result) {
var trainerJSON = result.data.courseTrainer;
var trainers = [];
for (var i = 0; i < trainerJSON.length; i++) {
trainers.push(trainerJSON[i].text);
}
$scope.courseName = result.data.courseName;
$scope.courseTrainer = trainers;
$scope.courseTrainerPage = result.data.courseTrainerPage;
$scope.courseDescription = $sce.trustAsHtml(result.data.courseDescription);
$scope.courseCategory = result.data.courseCategory;
$scope.courseDocuments = result.data.courseDocuments;
});

});

我通过 karma 为它写了一个测试用例:

  describe("SetCourseCtrl Unit testing #5", function() {
var controller, $controller, $scope, $rootScope, createController, $window;
beforeEach(angular.mock.module("myApp"));
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
$httpBackend = $injector.get('$httpBackend');
createController = {
setCourse: function() {
return $controller('SetCourseCtrl', {
$scope: $rootScope
});
}
}
}));

it('Test 2: post /course/getCourse', inject(function($controller) {
controller = createController.setCourse();
var path = $window.location.pathname;
path = path.split('/');
var courseID = path.pop();
var result = {
data: {
courseName: 'agile',
courseTrainerPage: 'trainer page',
courseDescription: 'description',
courseCategory: 'category',
courseDocuments: 'doc.pdf'
}
};
$httpBackend.whenPOST('/course/getCourse', {
courseID: courseID
}).respond(result);
$httpBackend.flush();
expect($rootScope.courseName).toBe(result.data.courseName);
expect($rootScope.courseTrainerPage).toBe(result.data.courseTrainerPage);
expect($rootScope.courseDescription).toBe(result.data.courseDescription);
expect($rootScope.courseCategory).toBe(result.data.courseCategory);
expect($rootScope.courseDocuments).toBe(result.data.courseDocuments);

}));

});

但是当我运行这个测试时,发生了一个错误:

PhantomJS 2.1.1 (Windows 8 0.0.0) SetCourseCtrl Unit testing #5 Test 2: post /course/getCourse FAILED Error: Unexpected request: POST /course/getCourse

谁能帮我解释一下?我认为它是因为 $window.location.pathname 而发生的,我不能模拟它,但我不确定。

最佳答案

错误消息说,对 /course/getCourse 的 POST 请求是意外的。

你需要像这样插入一个期望行:

$httpBackend.whenPOST('/course/getCourse', {
courseID: courseID
}).respond(result);
$httpBackend.expectPOST('/course/getCourse');
$httpBackend.flush();

关于angularjs - 使用 $window.location.pathname 对 angularjs 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38970701/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com