零食栏和 fakesync 的 Angular 测试问题

问题描述 投票:0回答:1

当我测试 Angular Material 小吃栏时,将持续时间设置为 3000 毫秒,然后在勾选 3000 后尝试使用 fakeAsync 进行测试,小吃栏仍然显示。如何让它自动关闭? 代码

angular angular-material karma-jasmine angular-test
1个回答
0
投票

您可以使用 Promise 来模拟

tick
并等待 3100ms,然后检查是否已解雇。

辅助功能:

export const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));

测试用例:

it('should open a snackbar with the provided message', async () => {
  const message = 'Test message';
  component.openSnackBar(message, 'Test Action');
  const snackBar = await loader.getHarness(MatSnackBarHarness);
  expect(await snackBar.getMessage()).toBe(message);
  console.log(await snackBar.isDismissed());
  await delay(3100);
  console.log(await snackBar.isDismissed());
  expect(await snackBar.isDismissed()).toBe(true);
});

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.