2
我有一個服務設置,它使我所有的AJAX調用。我想測試我的登錄方法,該方法將AJAX POST $http.post
發送到特定的URL,該URL返回結果(登錄通過或失敗)的對象。這個結果是一個對象。我沒有完全返回代碼來測試服務,但我試圖首先測試URL。這是它現在的樣子:Angular Js - 用Jasmine返回一個對象的測試POST請求
'use strict';
describe('Service: Ajax', function() {
var service, httpBackend;
// load the service's module
beforeEach(module('mySampleApp'));
// instantiate service
beforeEach(inject(function (Ajax, _$httpBackend_) {
httpBackend = _$httpBackend_;
service = Ajax;
}));
it('Test AJAX call', function() {
httpBackend.expect('POST', 'http://myloginurl', {u: 'xyz', p: 'pass'}, { withCredentials: true})
.respond(201, 'success');
});
});
這就過去了。現在我試着把一個錯誤的URL,錯誤的用戶名/密碼,但它仍然通過!我如何測試這個?
UPDATE: 寫得現在:
//Ajax is my AJAX service
it('should test the login AJAX call', inject(function (Ajax) {
httpBackend.expect('POST', 'http://myloginurl')
.respond(200, "[{ status: 200, //some more data }]");
httpBackend.flush();
Ajax.authenticate({u: 'xyz', password: 'pass' })
.then(function(data){
expect(data.status).toBe(200);
});
}));
我得到這個:
PhantomJS 1.9.7 (Linux) Service: Ajax should test the login AJAX call FAILED
Error: No pending request to flush !
blah blah...
我正在更新我的問題並添加我得到的響應。請檢查一下! – 2014-09-29 11:30:15
另外,'httpBackend.expect(...)'這個AJAX調用是否正確? – 2014-09-29 11:33:26
不,httpBackend.expect(...)不會執行調用 - 它告訴httpBackend期待一個調用。 httpBackend.flush()然後處理所有的調用。在這兩件事之間的某處,您需要調用執行ajax請求的函數。 – Fordio 2014-09-29 11:37:00