Angular4测试Karma - 错误:无法解析RequestOptions的所有参数:(?)

时间:2018-03-26 09:18:38

标签: angular unit-testing testing angular-cli karma-jasmine

这是我的spec.ts文件。我坚持错误:

  

错误:无法解析RequestOptions的所有参数:(?)

我已经导入了所有必需的提供者。有人可以帮我解决这个错误吗?

import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { ResetPasswordComponent } from './reset-password.component';
import { ConfigService } from './../config-service.service';
import {Http, Headers, ConnectionBackend, RequestOptions} from '@angular/http';

describe('ResetPasswordComponent', () => {
  // let component: ResetPasswordComponent;
  // let fixture: ComponentFixture<ResetPasswordComponent>;

   beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ResetPasswordComponent, ConfigService, Http, ConnectionBackend, RequestOptions]
    });
  });

  // beforeEach(async(() => {
  //   TestBed.configureTestingModule({
  //     declarations: [ ResetPasswordComponent ]
  //   })
  //   .compileComponents();
  // }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ResetPasswordComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  // it('should create', () => {
  //   expect(component).toBeTruthy();
  // });

  it('should create', () => {
    expect('holaa').toBe('holaa');
  });

  it('Is Password Change Function Working', inject([ResetPasswordComponent], (reset:ResetPasswordComponent) => {
    expect(reset.simplyAFunction()).toBe(true);
  }));
});

1 个答案:

答案 0 :(得分:3)

使用HttpHeaders时遇到的类似情况,希望我的经验对您有所帮助。 无论是在构建服务中还是写给我们,单元测试总是尝试模拟服务。

因此,在这种情况下,您可以像这样模拟RequestOptions。  将您的提供商更改为

providers: [ResetPasswordComponent, ConfigService, Http, ConnectionBackend, { provide: RequestOptions, useValue: RequestOptionsMock }]

通过在单元测试系统中执行此操作,将查找模拟的RequestOptions而不是原始的RequestOptions,然后,只要提供我们在代码中使用的属性,我们就可以编写类似的模拟的RequestOptions

一个模拟对象示例可能是这样

 const RequestOptionsMock = function(){
     return 'mockedResponse';
}

附加说明 这是角度文档https://angular.io/api/http/RequestOptions

中的原始RequestOptions
class RequestOptions {
constructor(opts: RequestOptionsArgs = {})
method: RequestMethod | string | null
headers: Headers | null
body: any
url: string | null
params: URLSearchParams
search: URLSearchParams
withCredentials: boolean | null
responseType: ResponseContentType | null
merge(options?: RequestOptionsArgs): RequestOptions
}