0

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!');
    })
  • does the `By.css('p')` return null or the `bannerDe.query(By.css('p'))`? – DaveExotic Jan 29 '23 at 17:54
  • bannerDe.query(By.css('p')) returns null & By.css('p') returns debugElement with length 1 – Reza Younesi Jan 29 '23 at 18:07
  • Do you import the correct `By` class from `@angular/platform-browser` – DaveExotic Jan 29 '23 at 18:17
  • Yeah I do. I’ve used @angular/platform-browser – Reza Younesi Jan 29 '23 at 19:14
  • I used commonjs in our tsconfig:{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es2017", "dom"], "noImplicitAny": false, "suppressImplicitAnyIndexErrors": true } } – Reza Younesi Jan 29 '23 at 23:25

2 Answers2

1

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')).

AliF50
  • 16,947
  • 1
  • 21
  • 37
0

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 } }