如何使用开玩笑和打字稿在对象上测试可能是两种不同类型的属性?

发布于 2025-01-25 19:05:06 字数 699 浏览 2 评论 0原文

我有一个函数getFruit()返回两种可能的类型,banana |苹果

我有一个开玩笑的单元测试,其中包括一种在其中一种类型上但不是另一种类型的属性测试。在这种情况下,香蕉具有属性peel,但Apple没有。

test(`gets a banana`, () => {
  const fruit = getFruit(id)
  expect(fruit?.peel).toBeDefined();
})

我满足于水果?.peel首次引用时可能无法定义它,因为我正在测试fruit?.peel在同一行中定义。

但是,ts标记fruit?.peel行有错误:

Property 'peel' does not exist on type 'Banana | Apple'.
  Property 'peel' does not exist on type 'Apple'

如何使用JEST和TYSPRICT使用JEST和TYSPRICK的对象上测试属性?

i知道我可以用TS-ignore禁用TS编译器,但我希望解决方案而不是解决方法。

I have a function getFruit() that returns two possible types, Banana | Apple.

I have a jest unit test that includes a test for a property that exists on one of the types, but not the other. In this case, Banana has the property peel but Apple does not.

test(`gets a banana`, () => {
  const fruit = getFruit(id)
  expect(fruit?.peel).toBeDefined();
})

I am content that fruit?.peel may not be defined when it is first referenced, as I am testing for fruit?.peel being defined in the same line.

However TS marks the fruit?.peel line as having an error:

Property 'peel' does not exist on type 'Banana | Apple'.
  Property 'peel' does not exist on type 'Apple'

How can I test a property on an object that may be of two different types using Jest and TypeScript?

I know I can disable the TS compiler with a ts-ignore, but I am hoping for a fix rather than a workaround.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Saygoodbye 2025-02-01 19:05:06

虽然Typescript不能让您访问尚不清楚的属性,但它可以让您使用 operator中的检查其存在:

expect('peel' in fruit).toEqual(true);

或者正如Jonrsharpe指出的那样,最好做到最好。此:

expect(fruit).toHaveProperty('peel');

在失败情况下输出:

    expect(received).toHaveProperty(path)

    Expected path: "peel"
    Received path: []

    Received value: {"cultivar": "braeburn"}

而不是:

    expect(received).toEqual(expected) // deep equality

    Expected: true
    Received: false

While TypeScript won't let you access a property that isn't known to exist, it will let you check for its existence with the in operator:

expect('peel' in fruit).toEqual(true);

Or as jonrsharpe points out, it may be better to do this:

expect(fruit).toHaveProperty('peel');

which in the failing case outputs:

    expect(received).toHaveProperty(path)

    Expected path: "peel"
    Received path: []

    Received value: {"cultivar": "braeburn"}

rather than:

    expect(received).toEqual(expected) // deep equality

    Expected: true
    Received: false
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文