0

I need test components of my angular app. The Problem is every time I want to test something the karma testrunner shows me that error:

Error: Unexpected request: GET /foo
No more request expected

After some research it was clear that the test framework blocks all requests and I need to declare every request accepted in my test via:

beforeEach(inject(function ($httpBackend) {
    $httpBackend.expectGET("/foo").respond("bar");
}));

so I can do expectations on requests.

The Problem is that it seems like I cannot initialize my $httpBackend and load my module/app after that like shown here:

beforeEach(inject(function ($httpBackend) {
    $httpBackend.expectGET("/foo").respond("bar");
}));
beforeEach(module('myApplication'));

It fails with

Error: Injector already created, can not register a module!

But to load my module/app first and configure the $httpBackend after this it is too late:

beforeEach(module('myApplication'));
beforeEach(inject(function ($httpBackend) {
    $httpBackend.expectGET("/foo").respond("bar");
}));

fails with

Error: Unexpected request: GET /foo
No more request expected

it fails because I need to make an ajax request inside of my application configuration myapp.config(function(...) {.. doSomeAjax ..}

Any Idea how to solve the Problem?

4

1 回答 1

2

关于第一个问题:您可以像这样加载您需要的模块:

var $httpBackend; // reference for your it() functions
beforeEach(function () {
    module('myApplication');

    inject(function ($injector) {
        $httpBackend = $injector.get('$httpBackend');
    });
});

现在,关于意外请求问题,来自angularjs httpBackend 文档

生产中使用的 $httpBackend 总是以异步方式响应请求。如果我们在单元测试中保留这种行为,我们将不得不创建异步单元测试,这很难编写、遵循和维护。同时测试模拟,不能同步响应,因为这会改变被测代码的执行。出于这个原因,模拟 $httpBackend 有一个 flush() 方法,它允许测试显式地刷新挂起的请求,从而保留后端的异步 api,同时允许测试同步执行。

我用的和你有点不同,所以我下面的解决方案只是一个猜测。首先,我认为您需要有一个模拟响应。你用 定义它when()...respond()。然后,您应该刷新您的请求:

$httpBackend.expectGET("/foo").respond("bar");
$httpBackend.flush();

我用它来测试在工厂发出 http 请求的服务。在 beforeEach 子句中,我首先定义了模拟响应,然后实例化了服务(myservice = $injector('nameofservice')然后我刷新了在工厂中触发的请求。

于 2013-07-18T13:24:37.317 回答