The component:
export class HomePage implements OnInit {
public flag = false;
constructor(private authService: AuthService) {
console.log("HomePage Created");
this.authService.subject.subscribe(res => {
this.flag = res;
})
}
ngOnInit() {
}
}
The service:
export class AuthService {
public subject = new BehaviorSubject(false);
constructor(private storage: Storage) {
console.log("AuthService created");
this.storage.create().then(() => {
this.storage.set('token', true).then(() => {
this.storage.get('token').then(token => {
console.log("token sent");
this.subject.next(token);
})
})
});
}
}
The tests:
describe('HomePage', () => {
let component: HomePage;
let fixture: ComponentFixture<HomePage>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [IonicStorageModule.forRoot()],
});
fixture = TestBed.createComponent(HomePage)
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create', async () => {
await fixture.whenStable()
console.log("test run");
expect(component).toBeTruthy();
});
});
The test output:
24 05 2024 17:19:33.830:INFO [Chrome 115.0.0.0 (Linux x86_64)]: Connected on socket ZveuSQt62spdgsS6AAAF with id 45284113
LOG: 'AuthService created'
Chrome 115.0.0.0 (Linux x86_64): Executed 0 of 4 SUCCESS (0 secs / 0 secs)
LOG: 'HomePage Created'
Chrome 115.0.0.0 (Linux x86_64): Executed 0 of 4 SUCCESS (0 secs / 0 secs)
LOG: 'test run'
Chrome 115.0.0.0 (Linux x86_64): Executed 0 of 4 SUCCESS (0 secs / 0 secs)
LOG: 'token sent'
Chrome 115.0.0.0 (Linux x86_64): Executed 1 of 4 (skipped 3) SUCCESS (0.056 secs / 0.04 secs)
LOG: 'token sent'
TOTAL: 1 SUCCESS
The problem:
As you can see, the token is sent AFTER the tests run. This is a very simplified case of another use case where the DOM components are not updating because of the token not being received by the component before the tests run. Is there a way I can make sure the service triggers the value before the assertions run? I don’t want to mock the service, because I want to achieve integration test if possible.
I Tried multiple combinations of fixture.whenStable() and fixture.detectChanges() but no luck