我正在使用angular material stepper在我的组件中导航,点击下面的按钮:
下面是我的按钮代码< stepper.component.html disabled="myService.disableNextButton(stepper.selectedIndex)"> Next
然后我有一个使用behaviorSubject来存储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;
}
}我正在使用JEST test和ts-mockito来模拟我的服务,如下所示:
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),
}
]
});
});在我的测试中,我有以下内容:
const nextButton = screen.getByRole('button', { name: 'next' });
expect(nextButton).toBeDisabled();问题是,当我使用原始服务时,按钮在启动时被禁用,但当我模拟该服务时,它并没有禁用它。你知道会出什么问题吗?
发布于 2021-02-08 16:20:59
我不能完全确定when/thenReturn语法是否正确。我通常会把它写成myServiceMock.disableNextButton.mockReturnValue(true)或myServiceMock.disableNextButton.mockReturnValueOnce(true)。
此外,在您的disableNextButton函数中,只需立即返回this.productDetails.value.productId == 0 (无用的if子句)。
https://stackoverflow.com/questions/66097870
复制相似问题