繁体   English   中英

Angular 8 使用 Karma 和 Jasmine 进行测试 NullInjectorError: R3InjectorError(DynamicTestModule)[api -> api]: NullInjectorError: No provider for Z8A5DA52ED126447D359E7

[英]Angular 8 Testing with Karma and Jasmine NullInjectorError: R3InjectorError(DynamicTestModule)[api -> api]: NullInjectorError: No provider for api

业力错误消息:

业力错误消息

app.component.spec.ts 文件代码:

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing'
import { HttpClientModule } from '@angular/common/http';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        HttpClientModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'dalivalidb'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('dalivalidb');
  });

  it('should render title', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement;
    expect(compiled.querySelector('.content span').textContent).toContain('dalivalidb app is running!');
  });
});

我是测试新手 我正在尝试使用 Angular 提供的 Karma 和 Jasmine 运行我的第一个自动化测试。 我尝试过运行测试,但遇到了关于 API 的 3 次失败。 不幸的是,我没有找到任何有关如何处理此类错误的相关信息,而且我也不熟悉 API。 因此,如果有人遇到任何类似的问题或知道修复方法,我们将不胜感激!!

我尝试了多种方法,包括将导入添加到app.component.spec.ts

imports: [
        RouterTestingModule,
        HttpClientModule
         ],

您可以在dalivalidb.netlify.app上查看网站

您似乎依赖于api中的app.component.ts

像这样的东西:

constructor(private api: api, ...) {}

您必须为api提供模拟。

尝试这个:

let api: api;
describe('AppComponent', () => 
  beforeEach(async(() => {
    let mockApi = {}; // mock your API as a plain JavaScript object
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        HttpClientModule
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        { provide: api, useValue: mockApi } // provide the mock like so.
      ]
    }).compileComponents();
  }));

显示完整的app.component.ts ,我想我可以为您提供更多帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM