我试图弄清楚如何测试我的 AngularJS 服务,它依赖于$http
.
当使用$httpBackend
模拟该 AJAX 帖子 ( whenPOST
) 时,您发布的对象是否确定响应?
这是我的服务和我的测试,例如:
(function () {
"use strict"
var app = angular.module('cs');
app.service('PlateCheckService', ['$http', function ($http) {
return {
checkPlate: function (plateNumber) {
return $http.post('PlateCheck/Index', {
plateNumber: plateNumber
}).then(function (response) {
return {
message: response.data.VehicleAtl === null ? 'Clean' : 'Hot',
alertClass: response.data.VehicleAtl === null ? 'alert-success' : 'alert-danger'
}
});
}
}
}]);
}());
测试
/// <reference path="../libs/angular-1.0.8/angular.js" />
/// <reference path="../libs/angular-1.0.8/angular-mocks.js" />
/// <reference path="../libs/jasmine-1.3.0/jasmine.js" />
/// <reference path="../app.js" />
/// <reference path="../services/plate-check-service.js" />
describe('Plate Check Service', function () {
var httpBackend,
service;
beforeEach(function () {
module('cs');
inject(function ($httpBackend, PlateCheckService) {
httpBackend = $httpBackend;
httpBackend.whenPOST('PlateCheck/Index', { plateNumber: '123456' }).respond({
response: {
message: 'Clean',
alertClass: 'alert-success'
}
});
httpBackend.whenPOST('PlateCheck/Index', { plateNumber: '123456789' }).respond({
response: {
message: 'Hot',
alertClass: 'alert-danger'
}
});
service = PlateCheckService;
});
});
it('Should return a clean plate.', function () {
var result;
service.checkPlate('123456').then(function (response) {
result = response;
});
httpBackend.flush();
expect(result.message).toBe('Clean');
expect(result.alertClass).toBe('alert-success');
});
});
测试结果
Test 'Plate Check Service:Should return a clean plate.' failed
Expected 'Hot' to be 'Clean'.
Expected 'alert-danger' to be 'alert-success'.
in D:\Code\Scripts\angular\specs\plate-check-service-specs.js (line 35)
0 passed, 1 failed, 1 total (chutzpah).
========== Total Tests: 0 passed, 1 failed, 1 total ==========
看起来它没有考虑到plateNumber
我传递给将其发布到服务器的服务。
我原以为这个测试会通过。
这有任何意义吗?