我測試的angularjs控制器,使用也嘲笑,但它引發的錯誤「錯誤:Unsatisfied requests: POST /myurl
測試:unsatistifed POST請求
我的測試文件中包含一個beforeEach方法這樣
httpBackend.whenPOST('/myurl')
.respond(200,obj1);
httpBackend.expectPOST('/myurl')
scope = $rootScope.$new();
MainCtrl = $controller('MyCtrl', {
$scope:scope
});
和我的測試情況是:
it('scope.mymethod should work fine', function(){
httpBackend.flush()
// verify size of array before calling the method
expect(scope.myobjs.length).toEqual(2)
// call the method
scope.saveNewPage(myobj)
// verify size of array after calling the method
expect(scope.myobjs.length).toEqual(3)
})
的方法saveNewPage
樣子:
function saveNewPage(p){
console.log('Hello')
$http.post('/myurl', {
e:p.e, url:p.url, name:p.name
}).then(function (response) {
otherMethod(new Page(response.data.page))
}, handleError);
}
請注意,console.log('Hello')
永遠不會執行(在業力控制檯它從來沒有打印)。
編輯: 與此同時,我正在研究有關httpBackend的文檔,我試圖改變httpBackend.flush()的位置。基本上,我正在執行第一次flush(),初始化範圍中的數據,然後執行該方法,然後爲未決請求執行其他flush()。具體而言,在這種情況下,測試案例是這樣的:
it('scope.saveNewPage should work fine', function(){
var p=new Object(pages[0])
httpBackend.flush()
httpBackend.whenPOST('/myurl',{
url:pages[0].url,
existingPage:new Object(pages[0]),
name:pages[0].name
}).respond(200,{data:pages[0]})
httpBackend.expectPOST('/myurl')
scope.saveNewPage(p)
httpBackend.flush()
expect(scope.pages.length).toBe(3)
})
但現在它提出了Error: No response defined !
,就像如果我沒有指定該URL
您可以嘗試用'existingPage:p'替換'existingPage:new Object(pages [0])'嗎? – Andyrooger