I have the follwing playwright test:
it("should throw an error when two components have the same id", () => {
expect(
(globalState.setComponent = {
component: "example",
id: "example",
config: new Example()
})
).rejects.toThrowError("Two components cannot have the same id");
});
should throw an error when two components have the same id
I’m trying to build a specialized state management system for my React components. Component’s must have an id. If none is supplied one is randomly generated. However, if two components have the same id an error is throwed.
Here is my class method to handle this:
public set setComponent(component: AddComponent) {
let tempComponent: Component = component as Component;
if (!component.id) {
tempComponent.id = "UI__" + nanoid();
} else {
tempComponent.id = component.id;
}
this.components.forEach((component) => {
if (component.id === tempComponent.id) {
throw new Error("Two components cannot have the same id");
}
});
this.components.push(tempComponent);
}
However when running my tests I get an error:
FAIL packages/etech-ui-utils/src/tests/global.spec.ts > #global > should throw an error when two components have the same id
Error: Two components cannot have the same id
❯ forEach packages/etech-ui-utils/src/Global.ts:45:15
43| this.components.forEach((component) => {
44| if (component.id === tempComponent.id) {
45| throw new Error("Two components cannot have the same id");
| ^
46| }
47| });
❯ Global.set setComponent [as setComponent] packages/etech-ui-utils/src/Global.ts:43:21
❯ packages/etech-ui-utils/src/tests/global.spec.ts:58:32
This is expected. My tests intentionally pass two of the same ids (the other is in a different test). However, I thought using expect(Throw new Error("An error").rejects.toThrowError("An error")
would make a succesful test.
- I have tried the
.throws
method and I still get the same error. - I have also tried calling expect asynchronously to no avail
A similar topic has been addressed in Stack Overflow however it does not solve my problem How to assert for errors in Playwright?