微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 组件测试没有服务提供者

如何解决Angular 组件测试没有服务提供者

我有一个组件、服务和模拟服务。我正在为组件编写一个简单的测试,但在测试时出现错误。我想使用 通过 useClass MyMockService 而不是 MyService。

角度版本:11.0.6 节点版本:14.15.4

组件:

export class MyComponent implements OnInit,OnDestroy {
    constructor(
      private sharedService: MySharedService,private myService: MyService) {}
    ...
}

规范文件

import { CommonModule } from '@angular/common';
import { ComponentFixture,Testbed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MyService } from '../my.service';
import { MySharedService } from '../my-shared.service';
import { MyMockService } from '../my.service.mock';

import { CountriesComponent } from './countries.component';

describe('MyComponent',() => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let service: MyService;

  beforeEach(async () => {

    await Testbed.configureTestingModule({
      declarations: [MyComponent],imports: [
        CommonModule,ReactiveFormsModule,],providers: [
        { provide: MyService,useClass: MyMockService },// <--
        MySharedService,})
      .compileComponents();
  });

  beforeEach(() => {
    fixture = Testbed.createComponent(MyComponent); // <-- ERROR !!!

    service = Testbed.inject(MyService);

    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

我的服务:

@Injectable()
export class MyService extends MyBaseService {

  baseUrl = '/baseUrl/...';
  constructor(
    protected hc: HttpClient
  ) {
    super(hc);
  }

  get() {
    return this.hc.get<any[]>(`${this.baseUrl}`);
  }

}

my.service.mock:

@Injectable()
export class MyMockService {

    arr: any[] = [];

    constructor(
    ) { }

    get() {
        return of(JSON.parse(JSON.stringify(this.arr)));
    }
}

创建组件时出现错误

NullInjectorError: R3InjectorError(DynamicTestModule)[MyService -> MyService]: 
  NullInjectorError: No provider for MyService !

我该如何解决这个问题?

解决方法

问题出在文件路径上。我有另一个同名的服务。 我改变了路径

import { MyService } from '../my.service';

import { MyService } from '../right path/my.service';

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。