【问题标题】:Angular Unit tests failing with undefined / no providerAngular 单元测试因未定义/没有提供者而失败
【发布时间】:2020-12-14 20:40:26
【问题描述】:

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

我正在使用 Karma 和 Jasmine 在 Angular 10 开发环境中进行测试

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

实际组件:Archiduserstoryoverview.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);
  }
}

测试组件:Archiduserstoryoverview.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 后端的一个 sn-p。

现在,当我运行所有测试时,它会出现以下三个错误:

我不确定“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)

真的很奇怪,AngularFireDatabase 甚至都没有创建,因为我完全在模拟自己的控制器

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$1.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)

这个有道理,测试不通过

预计未定义是真实的。

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)

我非常坚持这一点,我已经重写了我多次模拟的方式,我似乎真的无法解决它,如果有人请有时间帮我一把吗?如果您想查看任何其他文件,请告诉我。

【问题讨论】:

    标签: angular typescript unit-testing mocking jasmine


    【解决方案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();
      }));
    

    【讨论】:

    • 感谢您的回答,它解决了我遇到的一些问题,其他大部分问题都通过将非异步代码移动到异步代码末尾来解决
    猜你喜欢
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2019-05-15
    • 2015-04-03
    • 2017-08-23
    相关资源
    最近更新 更多