0
範圍變量我有我的模塊中定義的控制器如下,無法訪問茉莉測試用例
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':'[email protected]', '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": "[email protected]",
"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:"[email protected]",
password:"test"
}});
//flush response
httpBackend.flush();
expect(scope.loginResult).toEqual(expectedResponse);
}));
});
});
然而,當我運行測試時,我得到下面的錯誤
Expected undefined to equal Object({ success: true }).
我想響應數據從我的HTTP調用expectedResponse比較,如果兩者相等,則測試應該通過。
但是,我無法訪問我的測試用例中的$scope
變量loginResult。誰能告訴我我在這裏做錯了什麼?
有人可以描述使用茉莉花模擬HTTP調用的最佳方法嗎?
喜的第一行定義的
當我打電話submitForm,我得到錯誤類型錯誤:無法讀取屬性「電子郵件'的未定義 –
這是因爲在你的範圍內,確保你已經在測試的第一行定義了'$ scope.user = {email:'test @ gmail.com,password:'test'}' '('檢查用戶是否有效',注入(函數($ http){')。 –
謝謝戴安娜。你是對的! –