使用React-Testing-Library的渲染方法不起作用

时间:2019-08-17 10:44:03

标签: reactjs jestjs react-testing-library

我正在尝试测试react-testing-library文档中提供的基本示例。 我完全复制并粘贴了此代码here

无论如何都失败了。

以下是失败的测试结果:

shows the children when the checkbox is checked

    TypeError: Cannot read property 'current' of undefined

      34 | test('shows the children when the checkbox is checked', () => {
      35 |   const testMessage = 'Test Message'
    > 36 |   const {queryByText, getByLabelText, getByText} = render(
         |                                                    ^
      37 |     <HiddenMessage>{testMessage}</HiddenMessage>,
      38 |   )
      39 | 

      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:983:55)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1418:12)
      at render (node_modules/@testing-library/react/dist/pure.js:82:26)
      at Object.<anonymous> (src/components/Authentication/SignUp/index.test.js:36:52)

  ● shows the children when the checkbox is checked

    TypeError: Cannot read property 'current' of undefined

      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:983:55)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1418:12)
      at node_modules/@testing-library/react/dist/act-compat.js:57:20
      at asyncAct (node_modules/@testing-library/react/dist/act-compat.js:38:14)
      at Object.<anonymous> (node_modules/@testing-library/react/dist/index.js:28:35)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.318s, estimated 3s
Ran all test suites related to changed files.

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我在研究中也遇到了这个问题,看起来undefined被调用的currenthttps://github.com/facebook/react/blob/master/packages/react-dom/src/test-utils/ReactTestUtilsAct.js#L79内的IsSomeRendererActing

看起来像是在React包之间共享的全局变量。我能给的最好的建议是检查react dom react和react test utils以及任何其他react软件包都处于同一版本

答案 1 :(得分:0)

此错误可能来自HiddenMessage组件内部,而不是测试代码中的任何错误。似乎您正在尝试访问current上不存在的内容(可能是ref?)

测试代码看起来正确,您应该在current中找到要访问HiddenMessage的位置。