【问题标题】:Setup service provider on unit testing在单元测试中设置服务提供者
【发布时间】:2023-01-19 01:42:25
【问题描述】:

我有一个组件如下:

TS

export class CashFlowSalariesComponent implements OnInit, OnChanges {

...

constructor(
    public apiService: ApiService,
    private modalService: NgbModal,
    private toastr: ToastrService
  ) {}

  ngOnInit() {

  }
}

现在我想为它创建一个单元测试,所以我尝试

.spec.ts

describe('CashFlowSalariesComponent', () => {
    let component: CashFlowSalariesComponent;
    let fixture: ComponentFixture<CashFlowSalariesComponent>;
    let apiService: ApiService;


  
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        imports: [
                            [RouterModule.forRoot([])],
                            RouterTestingModule,
                            FormsModule,
                            ReactiveFormsModule,
                            BrowserModule,
                            HttpClientTestingModule,
                        ],
        declarations: [ 
            CashFlowSalariesComponent,
        ],
        providers: [{provide: apiService}]

      })
      .compileComponents();
    }));
  
    beforeEach(() => {
      fixture = TestBed.createComponent(CashFlowSalariesComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('should create', () => {
      expect(component).toBeTruthy();
    });

但这是抛出一条错误消息:

空注入器错误: StaticInjectorError(DynamicTestModule)[CashFlowSalariesComponent -> ApiService]:StaticInjectorError(平台: 核心)[CashFlowSalariesComponent -> ApiService]: NullInjectorError:没有 ApiService 的提供者!

如您所见,我尝试将 ApiService 设置为提供者,但没有成功;我究竟做错了什么?

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    provide 应该接收一个类,然后你也可以声明 useClass 或 useValue 如果你想存根它。

    providers: [{provide: ApiService, useValue: {methodExample: ()=>null}}]
    

    如果你不想模拟服务,你可以直接将类添加到提供者:

     providers: [ApiService]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-23
      • 2017-12-21
      • 2020-06-28
      • 2016-10-06
      • 2021-07-29
      • 2018-10-05
      • 1970-01-01
      • 2020-05-01
      相关资源
      最近更新 更多