モックも使用して angularjs コントローラーをテストしていますが、「エラー:Unsatisfied requests: POST /myurl
私のテスト用ファイルには、このような 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のモックを指定しなかった場合のように、今は発生します