You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright中toThrowError断言正确错误仍致测试失败

问题分析与解决

你的测试失败有两个核心原因:

1. 同步错误未被正确捕获

你的setComponent是同步的setter方法,但你误用了.rejects(这是专门处理异步Promise的断言方法),而且直接执行赋值操作会在expect外部就抛出错误,根本没被断言逻辑捕获。

正确的做法是把赋值操作包裹在一个函数中传给expect,让expect去执行这个函数并捕获同步抛出的错误。

2. 测试场景不成立

当前测试只调用了一次setComponent,此时this.components是空数组,forEach不会遍历任何元素,自然不会触发重复ID的错误判断。你需要先添加一个相同ID的组件,再执行第二次赋值才会触发预期的错误。


修改后的测试代码

it("should throw an error when two components have the same id", () => {
  // 先添加第一个ID为"example"的组件
  globalState.setComponent = {
    component: "example",
    id: "example",
    config: new Example()
  };

  // 用函数包裹第二次赋值操作,让expect捕获同步错误
  expect(() => {
    globalState.setComponent = {
      component: "example",
      id: "example",
      config: new Example()
    };
  }).toThrowError("Two components cannot have the same id");
});

额外优化建议

你的setComponent setter里用forEach遍历检查重复ID,效率较低,建议改用some方法,一旦找到重复就立即抛出错误,无需遍历全部元素:

public set setComponent(component: AddComponent) {
  let tempComponent: Component = component as Component;

  if (!component.id) {
    tempComponent.id = "UI__" + nanoid();
  } else {
    tempComponent.id = component.id;
  }

  // 改用some方法,提前终止遍历
  const hasDuplicateId = this.components.some(item => item.id === tempComponent.id);
  if (hasDuplicateId) {
    throw new Error("Two components cannot have the same id");
  }

  this.components.push(tempComponent);
}

内容的提问来源于stack exchange,提问作者Ethan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:32:18