Please help me to fix JEST unit-test.
There is a signal-condition block in the template. Initially this block isnt visible because the signal value is true. I need to find DIV via attribute inside this signal conditional block.
@Component({
selector: 'app-root',
standalone: true,
template: `
<p>i am app component!</p>
@if (!isLoading()) {
<div data-test="active-topic">qwerty</div>
}
`,
imports: [ChildComponent],
})
export class App {
isLoading: Signal<boolean> = signal(true);
}
To do this i write the following unit-test:
it('should exist active-topic element', () => {
component.isLoading = signal(false);
const elements = fixture.debugElement.queryAll(
By.css('[data-test="active-topic"]')
);
const elementsLength = elements.length;
toObservable(component.isLoading).subscribe((d) => {
expect(elementsLength).toBe(1);
});
});
As you see i try to assign FALSE value to isLoading variable and put expect to subscribe. However my unit test was failed. The error message is:
NG0203: toObservable() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with
runInInjectionContext
.
Can you help me to fix unit-test please?
The code does not need toObservable
, just trigger a fixture.detectChanges()
, so that the DOM is updated with the latest signal changes.
it('should exist active-topic element', () => {
component.isLoading = signal(false);
fixture.detectChanges();
const elements = fixture.debugElement.queryAll(
By.css('[data-test="active-topic"]')
);
const elementsLength = elements.length;
expect(elementsLength).toBe(1);
});