【发布时间】:2021-02-15 08:38:26
【问题描述】:
我正在使用注入器将数据从父组件传递到子组件。
export class ParentComponent OnInit {
...
public OpenStaffTerritory(staffTerritory: StaffTerritory) {
this.tabService.AddTab(staffTerritory.name, StaffTerritoryComponent, Injector.create({ providers: [{ provide: StaffTerritory, useValue: staffTerritory, deps: [] }], parent: this.injector }), true);
}
...
}
staff-territory.component.html:
<mat-card>
<form>
<div>
<div>
<mat-form-field>
<input matInput [(ngModel)]="staffTerritory.name" name="name">
</mat-form-field>
</div>
</div>
</form>
</mat-card>
staff-territory.component.ts:
@Component({
selector: 'app-staff-territory',
templateUrl: './staff-territory.component.html',
styleUrls: ['./staff-territory.component.scss']
})
export class StaffTerritoryComponent implements OnInit {
public staffTerritory: StaffTerritory;
constructor(staffTerritory: StaffTerritory) {
if (staffTerritory != undefined) {
this.staffTerritory = staffTerritory;
}
else {
this.staffTerritory = new StaffTerritory();
}
}
我正在尝试将假数据传递给组件并测试双向绑定是否有效,以及 DOM 中的字段是否具有所需的值。但到目前为止,我在测试中遇到错误,文本“错误:预期''包含'StaffTerritory'。”。请告诉我如何正确操作?
staff-territory.component.spec.ts:
describe('StaffTerritoryComponent', () => {
let component: StaffTerritoryComponent;
let fixture: ComponentFixture<StaffTerritoryComponent>;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
let staffTerritoryStub: StaffTerritory = {
id: 1,
name: 'StaffTerritory',
regionCode: 29,
createDate: new Date(),
creatorId: 0,
dateFrom: new Date(),
dateTo: null,
dateToSelect: new Date(),
dateFromChanger: 0,
dateToChanger: null,
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ StaffTerritoryComponent ],
imports: [
HttpClientTestingModule,
MaterialModule,
MatCardModule,
MatFormFieldModule,
FormsModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
],
providers: [
MatDialog,
{ provide: StaffTerritory, useValue: staffTerritoryStub },
{ provide: APP_CONFIG, useValue: APP_CONFIG }
]
})
.compileComponents();
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
}));
beforeEach(() => {
fixture = TestBed.createComponent(StaffTerritoryComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should render title in a input tag', () => {
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('input').textContent).toContain('StaffTerritory');
});
});
【问题讨论】:
标签: angular testing dependency-injection karma-jasmine