【问题标题】:Mocked service does not disable button in angular test?模拟服务不会在角度测试中禁用按钮?
【发布时间】:2021-02-08 08:08:40
【问题描述】:

我正在使用角度材料步进器在我的组件中导航,有以下按钮:

下面是我的 stepper.component.html 代码

然后我有一个使用 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 测试和 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();

问题是当我使用原始服务时,按钮在启动时被禁用,但是当我模拟服务时,它并没有禁用它。知道有什么问题吗?

【问题讨论】:

    标签: angular ts-jest angular-material-stepper ts-mockito


    【解决方案1】:

    我不确定when/thenReturn 语法是否正常。我通常会写成myServiceMock.disableNextButton.mockReturnValue(true)myServiceMock.disableNextButton.mockReturnValueOnce(true)

    另外,在您的 disableNextButton 函数中,只需立即返回 this.productDetails.value.productId == 0(无用的 if 子句)。

    【讨论】:

      猜你喜欢
      • 2020-06-24
      • 2021-06-19
      • 2016-01-09
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多