【问题标题】:Testing useEffect(), Hooks测试 useEffect(), Hooks
【发布时间】:2019-09-26 14:01:36
【问题描述】:

你好我是新的测试Hooks,所以我真的很迷茫,试图找到答案但没有结果。

所以问题是,我如何通过这段代码测试useEffect

代码:

const [ range, setRange ] = useState(DATE_OPTIONS.LAST_30_DAYS)
const [ isLoading, setIsLoading ] = useState(true)

const startLoading = () => setIsLoading(true)
const stopLoading = () => setIsLoading(false)

useEffect(() => {
    startLoading()
    fetchYearlyOptiDrive(range, objectId)
        .then(stopLoading)
        .catch(stopLoading)
}, [range, objectId])

我想从代码中测试的是LoadingIndicator,检查道具isLoading,如果是truefalse

<LoadingIndicator {...{ isLoading }} />

测试:

    test('should return the default value', () => {
        const wrapper = mount(<OptiDriveCard {...props} />)
        expect(wrapper.find('LoadingIndicator').props).toBeTruthy()
    })

错误:

Invariant Violation:元素类型无效:期望字符串(对于内置组件)或类/函数(对于复合组件)但得到:未定义

有什么建议吗?

【问题讨论】:

  • 根据您显示的错误,似乎某些组件不正确(错误表明某些组件返回 undefined 而不是字符串、类或函数)。如果您检查此sandbox,您将看到代码按预期运行。
  • @mgarcia 这是导入错误,抱歉 :(

标签: reactjs jestjs enzyme react-lifecycle-hooks


【解决方案1】:

要检查传递给组件的值,可以使用酶prop 方法。在你的情况下:

expect(wrapper.find('LoadingIndicator').prop('isLoading')).toBe(true);

【讨论】:

  • 现在这个TypeError: Cannot read property 'then' of undefined,对不起,我很菜鸟:(
  • 那将是您的 fetchYearlyOptiDrive 方法不返回承诺。您可以阅读有关承诺的信息here
猜你喜欢
  • 2020-03-20
  • 2020-11-01
  • 2021-01-14
  • 2020-05-07
  • 2020-01-24
  • 2021-10-22
  • 2020-12-28
  • 2019-11-22
  • 2021-06-29
相关资源
最近更新 更多