Angular 单元测试因未定义/无提供者而失败

Angular Unit tests failing with undefined / no provider

我真的需要一些帮助我有大约 12 个组件由于同样的问题而无法测试。我已经坐了大约 15 个小时,但确实没有取得太大进展,我想也许我的模拟是错误的。我将随机选择一个作为问题的示例。

我正在使用 Karma 和 Jasmine 在 Angular 10 开发环境

中进行测试

该组件称为 ArchivedUserStoryOverview,我制作了一个自己的控制器来与 Firebase 交互,我正在模拟这将 return 完全(或者至少我认为我正在做的)的可观察对象。请务必注意,我的应用 运行 没有在我测试时出现的错误问题。

实际分量:Archiveduserstoryoverview.component.ts

import { Component, OnInit } from '@angular/core';
import { FirebaseController } from '../../services/firebase-controller';
import { ActivatedRoute } from "@angular/router";

@Component({
  selector: 'app-archiveduserstoryoverview',
  templateUrl: './archiveduserstoryoverview.component.html',
  styleUrls: ['./archiveduserstoryoverview.component.css']
})
export class ArchiveduserstoryoverviewComponent implements OnInit {
  projectId: string;
  userstoryArray: Array<any>;
  assigneeArray: Array<string>;

  constructor(public firebaseController: FirebaseController, private route: ActivatedRoute) { 
    this.userstoryArray = new Array<any>();
    this.assigneeArray = new Array<string>();
    this.route.params.subscribe(params => this.setProjectId(params["id"]));
  }

  ngOnInit(): void {
    this.firebaseController.getUserstoriesSnapshot().subscribe(res => {
      res.forEach(item => {
        if(item.payload.val()['ProjectId'] == this.projectId){
          this.userstoryArray.push([item.key, item.payload.val()]);
          this.getUserNameByKey(item.payload.val()['AssignedUser']);
        }
      })
    });
  }

  setProjectId(id){
    this.projectId = id;
  }

  // Returns the username for a given user key
  private getUserNameByKey(userKey: string): any {
    this.firebaseController.getUserByKey(userKey).subscribe(a => {
      const data = a.payload.val();
      const id = a.key;
      this.assigneeArray.push(data['Name']);
    });
  }

  deArchiveUserstory(key){
    this.firebaseController.deArchiveUserstory(key);
  }
}

测试组件:Archiveduserstoryoverview.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ArchiveduserstoryoverviewComponent } from './archiveduserstoryoverview.component';
import {RouterTestingModule} from '@angular/router/testing';
import {FirebaseController} from '../../services/firebase-controller';
import {Observable, of} from 'rxjs';
import {AppModule} from '../../app.module';

describe('ArchiveduserstoryoverviewComponent', () => {
  let component: ArchiveduserstoryoverviewComponent;
  let fixture: ComponentFixture<ArchiveduserstoryoverviewComponent>;

  let fixtureUserstories = [
    {
      "-MFR0QIUc7tA3tAES5Zb" : {
        "AssignedUser" : "-MEZSC3KJvUynPd98kcH",
        "Description" : "",
        "EndDate" : "2020-02-22",
        "ProjectId" : "0",
        "SprintId" : "0",
        "Status" : "New",
        "Storypoints" : "",
        "Title" : "Frondend1"
      },
      "-MFRd7PsweHm07JUhZjA" : {
        "AssignedUser" : "",
        "Description" : "div links uitlijnen",
        "EndDate" : "2020-02-24",
        "ProjectId" : "0",
        "SprintId" : "-MFCHMDwfK84cVUdXosO",
        "Status" : "Archived",
        "Storypoints" : 1,
        "Title" : "About us fiksen"
      },
      "-MFRdG-biiv_okiRSWvi" : {
        "AssignedUser" : "-MEZSCn1yv9Yjo3eK4pr",
        "Description" : "nieuwe versie van angular",
        "EndDate" : "2020-02-25",
        "ProjectId" : "0",
        "SprintId" : "-MFCHMDwfK84cVUdXosO",
        "Status" : "New",
        "Storypoints" : 20,
        "Title" : "Updaten"
      }
    }
  ];
  let mockUserstories$ = of(fixtureUserstories);

  let fixtureUsers = [
    {
      "-MEZSC3KJvUynPd98kcH" : {
        "Name" : "Mitch"
      },
      "-MEZSCn1yv9Yjo3eK4pr" : {
        "Name" : "Maarten"
      },
      "-MEgdGlEPzDi1h32gTbH" : {
        "Name" : "John Doe"
      },
      "-MFYR3ln26SB8JjdE8eS" : {
        "Name" : "test"
      }
    }
    ]

  let mockUsers$ = of(fixtureUsers);

  beforeEach(async(() => {

    const fakeAFDB = jasmine.createSpyObj('FireBaseController', [ 'getUserstoriesSnapshot', 'getUserNameByKey']);

    fakeAFDB.getUserstoriesSnapshot.and.callFake(function() {
      return mockUserstories$;
    });

    fakeAFDB.getUserNameByKey('-MFYR3ln26SB8JjdE8eS').and.callFake(function() {
      return mockUsers$;
    });

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule, AppModule
      ],
      declarations: [ ArchiveduserstoryoverviewComponent ],
      providers: [ { provide: FirebaseController, useValue: fakeAFDB  }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ArchiveduserstoryoverviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

我首先创建用户故事和用户,该结构只是 Firebase 后端的一个片段。

现在,当我 运行 我所有的测试时,它给出了这三个错误:

我不确定在这种情况下“和”是什么意思,我曾经认为它在必须调用的方法中丢失了,我没有存根或模拟,但这似乎是假的

失败:无法读取未定义

的属性'and'
at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/views/archiveduserstoryoverview/archiveduserstoryoverview.component.spec.ts:75:54)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at AsyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.AsyncTestZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1032:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:289:1)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:363:1)
    at Zone.runGuarded (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:133:1)
    at runInTestZone (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1154:1)
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1092:1)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)

真的很奇怪,Angular甚至没有制作 FireDatabase,因为我完全在模拟我自己的控制器

NullInjectorError: R3InjectorError(DynamicTestModule)[FirebaseController -> AngularFireDatabase -> AngularFireDatabase]: NullInjectorError:AngularFireDatabase 没有提供程序!

error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'FirebaseController', 'AngularFireDatabase', 'AngularFireDatabase' ] })
    at <Jasmine>
    at NullInjector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:915:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11081:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11081:1)
    at injectInjectorOnly (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:801:1)
    at ɵɵinject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:805:1)
    at Object.FirebaseController_Factory [as factory] (ng:///FirebaseController/ɵfac.js:5:46)
    at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11248:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11070:1)
    at NgModuleRef.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:24198:1)
    at Object.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22101:1)

这个有道理,测试不通过

预期 undefined 为真。

Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/views/archiveduserstoryoverview/archiveduserstoryoverview.component.spec.ts:96:23)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:292:1)

我对此深信不疑,我已经重写了多次模拟的方式,但我似乎真的无法解决它,如果有人有时间帮助我吗?如果您想查看任何其他文件,请告诉我。

您最大的问题是您正在导入 AppModule。您的应用程序模块将引入模块的所有依赖项 - 您应该只导入该特定组件需要的内容,即 RouterTestingModule.

删除后,您应该不会再收到关于 AngularFireDatabase 的错误。可能发生的情况是,由于 AppModule 正在提供真正的 FirebaseController 服务,所以它首先使用来自 AppModule 的服务。

下一期 - 在您的组件中,您有一个名为 getUserNameByKey 的方法,它调用 this.firebaseController.getUserByKey。你的 fakeAFDB 应该有 getUserByKey.

第三期-

fakeAFDB.getUserNameByKey('-MFYR3ln26SB8JjdE8eS').and.callFake(function() {
      return mockUsers$;
    });

注意到你在这里是如何调用函数的了吗?对于任何假货,您都是在定义函数,而不是调用它。方法是 fakeAFDB.getUserByKey.and.callFake(function () { return mockUsers$; });

现在,以这种方式编写,无论传入什么,您都将返回完全相同的值。如果您想对其进行逻辑处理,您可以执行类似

的操作
fakeAFDB.getUserByKey.and.callFake(function (key) {
  if (key = 'some string'){
    return mockUsers$;
  }
  return someOtherResult;
});

这是您正在寻找的最终解决方案。这仍然会抛出错误,但是,在您调用 fixture.detectChanges 之后,因为控制器的 ngOnInit 中的代码查看 if(item.payload.val()['ProjectId'] == this.projectId){ 并且您的 getUserstoriesSnapshot 结果没有定义 val 函数.我相信你可以相应地修改你的假结果。

beforeEach(async(() => {
    const fakeAFDB = jasmine.createSpyObj<FirebaseController>('FireBaseController', ['getUserstoriesSnapshot', 'getUserByKey']);
    // returnValue is better here since you don't need logic on the return
    fakeAFDB.getUserstoriesSnapshot.and.returnValue(mockUserstories$);

    fakeAFDB.getUserByKey.and.callFake(() => {
      return mockUsers$;
    });

    TestBed.configureTestingModule({
      declarations: [ArchiveduserstoryoverviewComponent],
      imports: [RouterTestingModule],
      providers: [ { provide: FirebaseController, useValue: fakeAFDB  }]
    })
      .compileComponents();
  }));