我正在组件中使用mat表,并在更新表后调用renderRows,效果很好。 但是,在单元测试中,出现以下错误。
afterAll中引发了错误 失败:无法读取未定义的属性“ renderRows” 错误属性:Object({longStack:'TypeError:无法读取未定义的属性'renderRows' 在SafeSubscriber._next(http:// localhost:9876 / karma_webpack /src/app/product-management/tax-configuration/tax-configuration.component.ts:80:23)
spec.ts文件->
from ..proj1 import *
component.ts文件->
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TaxConfigurationComponent } from './tax-configuration.component';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NotificationService } from 'src/app/services/custom/notification.service';
import { TaxConfigurationService } from 'src/app/services/products/tax-configuration.service';
import { MockTaxConfigurationService } from 'src/app/services/products/tax-configuration.service.mock.spec';
import { throwError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
describe('TaxConfigurationComponent', () => {
let component: TaxConfigurationComponent;
let fixture: ComponentFixture<TaxConfigurationComponent>;
let _notificationService: NotificationService;
let _taxService: TaxConfigurationService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TaxConfigurationComponent],
imports: [
BrowserAnimationsModule,
MatTableModule,
MatFormFieldModule,
MatInputModule,
FormsModule,
ReactiveFormsModule,
HttpClientTestingModule,
MatButtonModule,
],
providers: [{ provide: TaxConfigurationService, useClass: MockTaxConfigurationService }],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TaxConfigurationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
_taxService = TestBed.inject(TaxConfigurationService);
_notificationService = TestBed.inject(NotificationService);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should populate tax table on init', () => {
expect(component.dataSource.length).toBeGreaterThan(0);
});
it('should show an error notification when "getTaxConfig()" errors out', () => {
spyOn(_notificationService, 'startNotification').and.callThrough();
spyOn(_taxService, 'getTaxConfig').and.returnValue(throwError('Error'));
component.ngOnInit();
expect(_notificationService.startNotification).toHaveBeenCalledWith(
'An error occurred while fetching data.',
'nc-notification--error',
'priority_high'
);
});
});
当我评论ngOnInit(): void {
this.state = true;
this.taxForm = new FormGroup({});
this.populateTaxConfigTable();
}
populateTaxConfigTable(): void {
this._taxService.getTaxConfig().subscribe((results) => {
results.forEach((result) => {
const rowEntry = {
name: result.resourceName,
category: result.resourceCategory,
id: result.resourceId,
tsc: new FormControl(result.taxTsc, [
Validators.required,
Validators.pattern(regexPattern),
Validators.max(100),
Validators.min(0),
]),
ot: new FormControl(result.taxOt, [
Validators.required,
Validators.pattern(regexPattern),
Validators.max(100),
Validators.min(0),
]),
vat: new FormControl(result.taxVat, [
Validators.required,
Validators.pattern(regexPattern),
Validators.max(100),
Validators.min(0),
]),
};
const tscControlName = rowEntry.id + 'tsc';
const otControlName = rowEntry.id + 'ot';
const vatControlName = rowEntry.id + 'vat';
this.taxForm.addControl(tscControlName, rowEntry.tsc);
this.taxForm.addControl(otControlName, rowEntry.ot);
this.taxForm.addControl(vatControlName, rowEntry.vat);
this.dataSource.push(rowEntry);
});
this.table.renderRows();
this.state = false;
}, (error) => {
this._notificationService.startNotification('An error occurred while fetching data.',
'nc-notification--error', 'priority_high');
});
}
时,单元测试正在运行,没有任何问题。对这个问题有任何想法吗?
编辑:
MockTaxCongfigurationService
this.table.renderRows
使用viewChild->
export class MockTaxConfigurationService {
getTaxConfig(): Observable<ResourceTaxes[]> {
return of([mockResourceTaxes, mockResourceTaxes]);
}
updateTaxConfig(data: TaxPostData[]): Observable<TaxResponseData[]> {
return of([mockTaxResponseData]);
}
}
答案 0 :(得分:0)
我认为您的单元测试实际上揭示了一个您没有遇到的问题,因为您的实际税收配置服务花费了足够长的时间,直到表格被初始化为止。
onInit中没有可用的视图子级。它在生命周期的后期设置。为此,您需要使用ngAfterViewInit
。
看看here
该错误在测试中显示,因为在fixture.detectChanges()
中的第一个beforeEach
内您正在触发ngOnInit
。您的税务服务模拟将立即发出您的模拟值,并且由于ViewChild
直到ngAfterViewInit
您的表仍为undefined