角单元测试失败,未定义/没有提供程序

如何解决角单元测试失败,未定义/没有提供程序

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

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

该组件称为ArchivedUserStoryOverview,我已经创建了一个自己的控制器来与Firebase进行交互,我在嘲笑将完全返回的可观察对象(或者至少是我认为的那样)。重要的是要注意,我的应用程序运行时没有出现测试时出现的错误问题。

实际组件:Archiveduserstoryoverview.component.ts

.popup-window {
  overflow: auto;
}

测试组件:Archiveduserstoryoverview.component.spec.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);
  }
}

我首先创建Userstories和Users,该结构只是Firebase后端的一小段。

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

我不确定在这种情况下“ And”是什么意思,我以前认为我没有进行存根或模拟的方法中缺少“ And”,但这似乎是错误的

失败:无法读取未定义的属性“和”

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","SprintId" : "-MFCHMDwfK84cVUdXosO","Status" : "Archived","Storypoints" : 1,"Title" : "About us fiksen"
      },"-MFRdG-biiv_okiRSWvi" : {
        "AssignedUser" : "-MEZSCn1yv9Yjo3eK4pr","Description" : "nieuwe versie van angular","EndDate" : "2020-02-25","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();
  });
});

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

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

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)

这很有意义,测试没有通过

期望未定义为真实。

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)

我对此深感难以置信,以至于我已经重写了多次模拟的方式,但我真的似乎无法解决它,如果有人请的话可以帮我一下吗?如果您要查看其他文件,请告诉我。

解决方法

最大的问题是您要导入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();
  }));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-