Issue
Often when I'm testing that a particular object/class is wired up correctly, I'll use it.each
in order to avoid writing a lot of repeated tests. Unfortunately, because the type in question doesn't have an index signature, I have to cast it to any to make it work:
class Foo {
bar = "string"
baz = "another-string"
}
test.each`
property | value
${"bar"} | ${"string"}
${"baz"} | ${"another-string"}
`("$property maps to $value", ({ property, value }) => {
const foo = new Foo()
expect((foo as any)[property]).toEqual(value)
});
Is there a way of doing this without using any?
Solution
Instead of asserting foo
as any
, you can assert the key to be a valid key of foo
:
expect(foo[property as keyof typeof foo]).toEqual(value);
An if statement could also work:
if (property in foo) expect(foo[property]).toEqual(value);
Answered By - merryweather
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.