【问题标题】:Angular4 Testing Karma - Error: Can't resolve all parameters for RequestOptions: (?)Angular4 测试业力 - 错误:无法解析 RequestOptions 的所有参数:(?)
【发布时间】:2018-03-26 09:18:38
【问题描述】:

这是我的 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);
  }));
});

【问题讨论】:

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


    【解决方案1】:

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

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

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

    通过在单元测试系统中执行此操作,系统将寻找模拟的 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
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2017-11-20
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 2017-01-21
      • 2017-11-13
      相关资源
      最近更新 更多