by.css always returns null [jasmine unit test ]

1.1k Views Asked by At

I have no idea why in my Angular project, Jasmin alwasys return null when I'm trying to access a HTML's element!

it('should find the <p> with fixture.debugElement.query(By.css)', () => {
    const bannerDe: DebugElement = fixture.debugElement;
    const paragraphDe = bannerDe.query(By.css('p'));
    const p: HTMLElement = paragraphDe.nativeElement;
    expect(p.textContent).toEqual('banner works!');
  });
<p class="title">banner works!</p>

I also have tried to call 'fixture.whenStable().then' but again it returns null!

it('should find the <p> with fixture.debugElement.query(By.css)', () => {
    const fixture = TestBed.createComponent(MobileAppLinkComponent);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
    const bannerDe: DebugElement = fixture.debugElement;
    const paragraphDe = bannerDe.query(By.css('p'));
    const p: HTMLElement = paragraphDe.nativeElement;
    expect(p.textContent).toEqual('banner works!');
    })
2

There are 2 best solutions below

0
AliF50 On

Most likely the p tag is hidden by an *ngIf. Can you try logging out the fixture.nativeElement to see if you see the p tag?

it('should find the <p> with fixture.debugElement.query(By.css)', () => {
    const bannerDe: DebugElement = fixture.debugElement;
    // !! Add this line to see if the p tag is there
    console.log(fixture.nativeElement);
    const paragraphDe = bannerDe.query(By.css('p'));
    const p: HTMLElement = paragraphDe.nativeElement;
    expect(p.textContent).toEqual('banner works!');
  });

If the p tag is not there, most likely it is being hidden by an *ngIf by a parent element. You will have to make this condition true, then fixture.detectChanges() so the HTML updates and then attempt to grab the p tag with fixture.debugElement.query(By.css('p')).

0
Reza Younesi On

I figure it out that my module in compilerOptions was commonjs in tsConfig.ts so I've updated it to es2020 and it worked as expected.

{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "target": "es5", "module": "es2020", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true } }