无法解析Jasmine测试中响应错误的所有参数

时间:2016-07-07 08:12:59

标签: typescript angular jasmine

我的测试中有这段代码:

import {
  beforeEach, beforeEachProviders,
  describe, xdescribe,
  expect, it, xit,
  async, inject
} from '@angular/core/testing';
import { UserService } from './user.service';
import { Http, ConnectionBackend, Response, Headers, RequestOptions } from '@angular/http';
import { Observable }     from 'rxjs/Observable';
import { LocalStorage, SessionStorage, WEB_STORAGE_PROVIDERS } from 'h5webstorage';

beforeEachProviders(() => [
  UserService, Http, Response, Observable, ConnectionBackend, LocalStorage, Headers, RequestOptions
]);

describe('Service: UserService', () => {

  it('testtest', inject([UserService], (service) => {
    expect('test').toEqual('test');
  }));
});

当我运行时,我收到以下错误:

  

错误:无法解析“响应”(?)的所有参数。确保这一点   所有参数都用Inject修饰或具有有效类型   注释和“响应”用Injectable修饰。

这是因为测试中不合适的依赖注入吗? 如何在Jasmine测试中进行适当的依赖注入?

1 个答案:

答案 0 :(得分:2)

这应该为你解决:

import { provide } from '@angular/core';
import {
    beforeEach, 
    addProviders,
    inject
} from '@angular/core/testing';
import { UserService } from './user.service';

import {BaseRequestOptions, Http, Response, ResponseOptions, RequestMethod} from '@angular/http';

import {MockBackend} from '@angular/http/testing';

describe('Service: UserService', () => {
    beforeEach(() => addProviders([
        UserService,
            BaseRequestOptions,
            MockBackend,
            provide(Http, {
                useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
                    return new Http(backend, defaultOptions);
                },
                deps: [MockBackend, BaseRequestOptions]
            })
        ]));

    it('testtest', inject([UserService], (service) => {
        expect('test').toEqual('test');
    }));
});

您需要为Http提供工厂。否则你将无法模仿回复。