I've done this plenty of times with no problems, but for some reason, I can't get this to work. In my component I have an input @Input data: Data
, and in my template I use that input to conditionally show or hide content. For some reason in my tests, the component won't register that the data is there even if I set it directly with component.data = {props: values}
, however if I run the tests individually with fit
, they run fine.
data.component.spec.ts
beforeEach(() => {
fixture = testbed.createComponent(DataComponent);
component = fixture.componentInstance;
component.data = {values: ['a', 'b', 'c']};
fixture.detectChanges();
component.ngOnInit();
fixture.detectChanges();
});
describe('when viewing', () => {
it('should load and display data', () => {
const el = fixture.debugElement.query(By.css('[data-content]'));
expect(el).toBeTruthy();
});
}
data.component.ts
export class DataComponent implements OnInit {
@Input() data!: Data;
constructor() {};
ngOnInit() {
console.log('init');
}
}
data.component.html
<div *ngIf="data.values.length">
<p data-content *ngFor="let value of data.values">{{value}}</p>
</div>
The error I'm getting: Expected null to not be null "[data-content]"
I am thinking it could be because you're calling fixture.detectChanges
and ngOnInit
. The first fixture.detectChanges
you call, calls ngOnInit
for you.
Try this:
beforeEach(() => {
fixture = testbed.createComponent(DataComponent);
component = fixture.componentInstance;
component.data = {values: ['a', 'b', 'c']};
fixture.detectChanges(); // => this will call ngOnInit
// component.ngOnInit(); // remove this line, the first fixture.detectChanges()
// calls ngOnInit for you.
});
describe('when viewing', () => {
it('should load and display data', () => {
const el = fixture.debugElement.query(By.css('[data-content]'));
expect(el).toBeTruthy();
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.