在angularjs测试中验证$ httpBackend上的调用

tan*_*khi 3 unit-testing jasmine angularjs

我正在尝试为angularjs编写一个测试$ httpBackend的测试.以下是测试.

describe('test', function() {

    beforeEach(function (){
        module('abcApp');
    });

    var $httpBackend, filterService;
    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        filterService = $injector.get('filterService');
    }));

    it('getCompany calls get on http with correct parameter', function () {
        $httpBackend.when('GET', 'api/Abc').respond([]);
        filterService.getAbc();
        $httpBackend.flush();
        expect($httpBackend.get).toHaveBeenCalled();
    });
});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我收到以下错误: - 错误:预期间谍,但未定义.

任何想法如何我断言$ httpBackend.get已使用expect使用必需参数调用.

JB *_*zet 5

expect($httpBackend.get).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

是无效的.首先是因为$ httpBackend没有任何(记录的)get()方法.其次,因为$ httpBackend.get没有被Jasmine监视,所以如果调用了这个方法你就不能添加Jasmine.

你应该测试一下,给定http后端返回的空数组,服务返回正确的东西,或者具有所需的副作用.你也可以用

$httpBackend.expectGET('api/Abc').respond([]);
Run Code Online (Sandbox Code Playgroud)

$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
Run Code Online (Sandbox Code Playgroud)

以便$ httpBackend验证您是否已发送预期请求.