【问题标题】:UseValue of a MockService in Jasmine unit test causes test failJasmine 单元测试中 MockService 的 UseValue 导致测试失败
【发布时间】:2021-05-08 02:47:57
【问题描述】:

我创建了一个 StackBlitz 并运行 karma/jasmine 加载程序,因此您可以看到测试通过/失败。

应用程序正在正常工作。

我的测试应该没问题并且会通过,但是使用模拟服务而不是createspyobject on 的正确服务时出现了一个奇怪的错误。

component.ts

  getReportFunc(): void {
    this.reportService.getReport(this.urn).subscribe(selectedReport => {
      this.model = selectedReport;
    });
  }

对服务的简单调用以获取“getReport”。我将添加一个测试来检查报告是否已被调用。但是不能因为这个问题。

spec.ts

describe("SearchComponent", () => {
  let component: SearchComponent;
  let fixture: ComponentFixture<SearchComponent>;
  let mockReportService;

  beforeEach(async(() => {
      mockReportService = jasmine.createSpyObj(['getReport']);
    TestBed.configureTestingModule({
      declarations: [SearchComponent],
      providers: [
        //ReportService,
            { provide: ReportService, useValue: mockReportService },
...

问题在于 { provide: ReportService, useValue: mockReportService } 仅使用 ReportService 会运行良好,但这意味着我无法运行我的一项测试。我想创建一个间谍对象mockReportService = jasmine.createSpyObj(['getReport']);

您将在StackBlitz 中看到的错误是TypeError: Cannot read property 'subscribe' of undefined

如果有人可以帮助我使用模拟服务运行它,以便我可以测试 getReport 订阅功能,我将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    问题来自滥用jasmine.createSpyObj 你有两个选择:

    1. 使用jasmine.createSpyObj,但要以正确的方式:
    // Note the first arg, you were missing it
    mockReportService = jasmine.createSpyObj(ReportService, ['getReport']);
    
    
    // Then, explain what to do with it :
    beforeEach(() => {
      [...]
      // When called, make it return an Observable so that the call to subscribe() succeeds
      mockReportService.getReport.and.returnValue(of({}));
      fixture.detectChanges();
    });
    
    1. 不要使用间谍

    当然,间谍很简洁,但只有当您想在不同的单元测试期间更改返回值时它们才有用。如果您只需要始终返回一个值,无论如何,您都可以选择这样的硬编码对象:

      const mockReportService = {
        getReport: () => of({})
      }
    
      providers: [
        { provide: ReportService, useValue: mockReportService },
    

    【讨论】:

      猜你喜欢
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多