我真的需要一些帮助,因为同样的问题,我有大约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",
"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();
});
});
真的很奇怪,因为我完全在模拟自己的控制器,所以甚至没有制作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)
我对此深感难以置信,以至于我已经重写了多次模拟的方式,但我真的似乎无法解决它,如果有人请的话可以帮我一下吗?如果您要查看其他文件,请告诉我。
答案 0 :(得分: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();
}));