I am using angular material stepper to navigate in my component have the below button:
Below is my stepper.component.html code <button [disabled]="myService.disableNextButton(stepper.selectedIndex)"> Next
Then I have a service that uses a behaviorSubject to store productId:
export class MyService {
product : any {
productId: 0,
ProductName: ''
}
private productDetails = new BehaviorSubject<ProductData>(this.product);
disableNextButton(step: number) : boolean{
if(this.productDetails.value.productId==0){
return true;
}
return false;
}
}
I am using JEST test and ts-mockito to mock my service as per below:
product : any {
productId: 0,
ProductName: ''
}
private productDetails = new BehaviorSubject<ProductData>(this.product);
const myServiceMock = mock(MyService);
beforeEach(async () => {
when(MyService.disableNextButton(anything())).thenReturn(
true
);
await render(StepperComponent, {
imports: [ReactiveFormsModule, MatStepperModule, MatButtonModule],
providers: [
{
provide: MyService,
useFactory: () => instance(myServiceMock),
}
]
});
});
In my test I have the below:
const nextButton = screen.getByRole('button', { name: 'next' });
expect(nextButton).toBeDisabled();
The problem is when I use the original service, the button is disabled on start, but when I mock the service, it does not disable it. Any idea what could be wrong?
I am not entierly sure if the
when
/thenReturn
syntax is ok. I usually would write that asmyServiceMock.disableNextButton.mockReturnValue(true)
ormyServiceMock.disableNextButton.mockReturnValueOnce(true)
.also, in your
disableNextButton
function, just returnthis.productDetails.value.productId == 0
instantly (useless if-clause).