Jasmine:期待$ http.post()没有被调用

W L*_*ert 10 jasmine angularjs karma-runner

在angularjs程序中,如果在测试中没有执行http帖子,我想用Jasmine进行测试.

我尝试以下代码:

expect($http.post).not().toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

但我得到"ReferenceError:$ http未定义"

efa*_*ley 7

这是旧的但我使用以下来测试这个.

expect($httpBackend.flush).toThrowError('No pending request to flush !');
Run Code Online (Sandbox Code Playgroud)


dnc*_*253 6

这是错误是因为你从未在测试中注入$ http.您可以使用inject函数执行此操作,但是对于测试$http调用,您确实应该使用$ httpBackend

对于要确保不调用它们的请求,您不需要执行任何操作.当Angular收到不期望的请求(由expect 函数on 定义$httpBackend)时,会抛出错误.因此,如果发出的请求不应该是,则测试将从意外请求引发的此错误中失败.

  • 好吧,在其他测试中,我测试是否使用`scope.httpBackend.expectPOST('MY_ENDPOINT',data)`调用$ http.post.现在在测试中我想测试没有发布请求.我没有在$ httpBackend中看到任何post方法来做一些测试:`expect(scope.httpBackend.post).not.toHaveBeenCalled();`注意在beforeEach中我在我的范围中注入$ httpBackend:`scope .httpBackend = $ httpBackend;` (2认同)
  • 这不完全正确.如果你不调用$ httpBackend.flush(),你将不会收到意外的请求错误.如果你确实调用$ httpBackend.flush()并且没有发出请求,你将收到一个No pending请求来刷新错误.肯定有更好的办法. (2认同)