【问题标题】:How to test for types on react components and props如何测试反应组件和道具的类型
【发布时间】:2020-03-09 02:36:30
【问题描述】:

我只是想在开箱即用的 react 测试工具上测试类型,它看起来很直接我想做的事情,但它就是不喜欢它。另外,其他类型可以吗?

test('Expect label to be of type string', () => {
  const testString = 'Test value'
  const { getByDisplayValue } = render(<Label text={testString}/>);
  expect(getByDisplayValue).toBe(string);
});

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    如果你想在 JavaScript 中测试某事物的类型,你可以使用 typeof 运算符,并且可以这样写一个期望:

    const aValue = 'Some string'
    expect(typeof aValue).toEqual('string')
    

    我不确定getByDisplayValue 来自哪里,但我也不希望它是一个字符串?它看起来像来自 testing library 的 API?

    【讨论】:

    • 看起来不错,但这不会测试组件的特定属性,getByDisplayValue 我认为这是我的&lt;Label/&gt; 组件的值
    • 我只是向您展示了一个测试一般事物类型的代码示例。我认为在没有任何其他库的情况下您会遇到的一个问题是您无法轻松地从组件中获取道具。我会建议 Enzyme 来测试这种东西
    猜你喜欢
    • 2021-04-07
    • 2021-12-29
    • 2016-04-28
    • 2017-11-20
    • 2019-06-30
    • 1970-01-01
    • 2018-10-09
    • 2021-04-09
    • 2021-09-07
    相关资源
    最近更新 更多