Unable to change input value for afterNextRender from unit test

I am trying to write unit test for my component but I am unable to change my input value inside afterNextRender

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// In component code
constructor() {
afterNextRender({
write: () => {
if (this.disabled()) {
this.myStream.next('hello');
}
}
});
}
// in unit test
it('should call the function when disabled is true', async () => {
fixture.componentRef.setInput('disabled', true);
await firstValueFrom(component.myStream);
expect(component.disabled()).toEqual(true);
});
</code>
<code>// In component code constructor() { afterNextRender({ write: () => { if (this.disabled()) { this.myStream.next('hello'); } } }); } // in unit test it('should call the function when disabled is true', async () => { fixture.componentRef.setInput('disabled', true); await firstValueFrom(component.myStream); expect(component.disabled()).toEqual(true); }); </code>
// In component code
constructor() {
  afterNextRender({
    write: () => {
      if (this.disabled()) {
        this.myStream.next('hello');
      }
    }
  });
}

// in unit test
it('should call the function when disabled is true', async () => {
 
  fixture.componentRef.setInput('disabled', true);

  await firstValueFrom(component.myStream);
  
  expect(component.disabled()).toEqual(true);
});

The test waits forever then fails. it seems that afterNextRender is executed in the constructor as soon as the component is created in the unit test, the input is false at that time, I need to be able to set the input first then call it to execute, similar to how we do with ngOnInit for instance. how can I do this test with afterNextRender?

You have to mock the method as true, through component inheritance.

The constructor is called, on the line fixture = TestBed.createComponent(TestingComponent);, so the spyOn, is too late, which might be the issue.


You can simply convert the subject to a BehaviourSubject, through inheritance and just for testing this one particular scenario.

After doing this test case, you can continue using AppComponent, Since subject is not possible to subscribe when the code is in the constructor.

Also one thing to note, is that the afterNextRender will execute immediately when working on a non SSR context. Hence you are facing so many difficulties.


Spec TS:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import {
TestBed,
ComponentFixture,
waitForAsync,
fakeAsync,
flush,
} from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { Component, input } from '@angular/core';
@Component({
// ... // <- values similar to your component
selector: 'my-app',
template: '',
})
export class AppComponentTesting extends AppComponent {
isDisabled: any = input(true);
myStream = new BehaviorSubject(null);
constructor() {
// ... // <- same values as YourComponent.
super(); // <- add args if needed. But your properties must be protected and not private.
}
}
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let output;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppModule],
declarations: [AppComponentTesting],
}).compileComponents();
});
// in unit test
it('should call the function when disabled is true', fakeAsync(() => {
const fixture: ComponentFixture<AppComponentTesting> =
TestBed.createComponent(AppComponentTesting);
const component: AppComponentTesting = fixture.componentInstance;
fixture.componentRef.setInput('disabled', true);
spyOn(component.myStream, 'next');
fixture.detectChanges();
flush();
expect(component.myStream.value).toEqual('hello');
}));
});
</code>
<code>import { TestBed, ComponentFixture, waitForAsync, fakeAsync, flush, } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { AppModule } from './app.module'; import { BehaviorSubject, firstValueFrom } from 'rxjs'; import { Component, input } from '@angular/core'; @Component({ // ... // <- values similar to your component selector: 'my-app', template: '', }) export class AppComponentTesting extends AppComponent { isDisabled: any = input(true); myStream = new BehaviorSubject(null); constructor() { // ... // <- same values as YourComponent. super(); // <- add args if needed. But your properties must be protected and not private. } } describe('AppComponent', () => { let component: AppComponent; let fixture: ComponentFixture<AppComponent>; let output; beforeEach(() => { TestBed.configureTestingModule({ imports: [AppModule], declarations: [AppComponentTesting], }).compileComponents(); }); // in unit test it('should call the function when disabled is true', fakeAsync(() => { const fixture: ComponentFixture<AppComponentTesting> = TestBed.createComponent(AppComponentTesting); const component: AppComponentTesting = fixture.componentInstance; fixture.componentRef.setInput('disabled', true); spyOn(component.myStream, 'next'); fixture.detectChanges(); flush(); expect(component.myStream.value).toEqual('hello'); })); }); </code>
import {
  TestBed,
  ComponentFixture,
  waitForAsync,
  fakeAsync,
  flush,
} from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { Component, input } from '@angular/core';

@Component({
  // ... // <- values similar to your component
  selector: 'my-app',
  template: '',
})
export class AppComponentTesting extends AppComponent {
  isDisabled: any = input(true);
  myStream = new BehaviorSubject(null);
  constructor() {
    // ... // <- same values as YourComponent.
    super(); // <- add args if needed. But your properties must be protected and not private.
  }
}

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let output;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [AppModule],
      declarations: [AppComponentTesting],
    }).compileComponents();
  });

  // in unit test
  it('should call the function when disabled is true', fakeAsync(() => {
    const fixture: ComponentFixture<AppComponentTesting> =
      TestBed.createComponent(AppComponentTesting);
    const component: AppComponentTesting = fixture.componentInstance;
    fixture.componentRef.setInput('disabled', true);
    spyOn(component.myStream, 'next');
    fixture.detectChanges();
    flush();
    expect(component.myStream.value).toEqual('hello');
  }));
});

TS:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Component, afterNextRender, input } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
disabled = input(true);
myStream = new Subject();
constructor() {
afterNextRender({
write: () => {
console.log('qwer', this.disabled());
if (this.disabled()) {
console.log('qwer1', this.disabled());
this.myStream.next('hello');
}
},
});
}
}
</code>
<code>import { Component, afterNextRender, input } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'my-app', templateUrl: './app.component.html', }) export class AppComponent { disabled = input(true); myStream = new Subject(); constructor() { afterNextRender({ write: () => { console.log('qwer', this.disabled()); if (this.disabled()) { console.log('qwer1', this.disabled()); this.myStream.next('hello'); } }, }); } } </code>
import { Component, afterNextRender, input } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent {
  disabled = input(true);
  myStream = new Subject();
  constructor() {
    afterNextRender({
      write: () => {
        console.log('qwer', this.disabled());
        if (this.disabled()) {
          console.log('qwer1', this.disabled());
          this.myStream.next('hello');
        }
      },
    });
  }
}

Stackblitz Demo

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật