我的模块中定义了一个控制器,如下所示,
myTestApp.controller("LoginController", function($scope,$http,$location) {
$scope.submitForm = function(){
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
$http({
url:'api/login/',
headers: {'Content-Type': 'application/json'},
method:'POST',
data:{
username:userEmail,
password:userPassword
}})
.success(function(data){
$scope.loginResult = data;
});
};
});
我正在尝试使用httpBackend
编写用于模拟HTTP调用的测试用例。
这是我的jasmine
测试代码:
describe('make HTTP mock call', function() {
var scope, httpBackend, http, controller;
beforeEach(module('myTestApp'));
describe('with httpBackend', function() {
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
http = $http;
controller = $controller('LoginController', {$scope : scope} );
httpBackend.when("POST", "api/login/",{'username':'test@gmail.com', 'password':'test'}, function(headers) {
return {
'Content-Type': 'application/json',
};
}).respond(200);
}));
afterEach(inject(function ($httpBackend){
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
it('to check if user is valid', inject(function ($http) {
var expectedResponse = { success: true };
httpBackend.expectPOST('api/login/', {
"username": "test@gmail.com",
"password": "test"
}, function(headers){
return headers['Content-Type'] === 'application/json';
}).respond(function(method, url, data, headers, params){
return [200, {}, {}];
});
//actual HTTP call
$http({
url:'api/login/',
headers: {'Content-Type': 'application/json'},
method:'POST',
data:{
username:"test@gmail.com",
password:"test"
}});
//flush response
httpBackend.flush();
expect(scope.loginResult).toEqual(expectedResponse);
}));
});
});
但是,当我运行测试用例时,我收到以下错误
预期未定义为等于Object({success:true})。
我想将HTTP调用的响应数据与expectedResponse进行比较,如果两者相等则测试应该通过。
但是,我无法从我的测试用例中访问$scope
变量loginResult。谁能告诉我我在这里做错了什么?
有人可以描述使用Jasmine模拟HTTP调用的最佳方法吗?
答案 0 :(得分:2)
只有在调用函数submitForm
时才会填充您的登录数据。因此,在测试中,在执行flush()
之前调用该函数。
更新: 确保您已定义
$scope.user={email :'test@gmail.com,password:'test'}
在测试的第一行(就在it('to check if user is valid', inject(function ($http) {
之后)