【问题标题】:create-react-app testing "React is not defined"create-react-app 测试“React 未定义”
【发布时间】:2019-08-23 19:03:40
【问题描述】:

我将react-scripts@2.1.8typescript@3.3.3jest@.23.6.0 一起使用并运行我的测试,它们因“未定义React”而失败。

 FAIL  src/components/Button/test.tsx
  ● <Button> › renders text correctly

    ReferenceError: React is not defined

       6 |     it('renders text correctly', () => {
       7 |         const text = 'hello there i am a test'
    >  8 |         const { getByText } = customRender(<Button>{text}</Button>)
         |                                            ^
       9 |         expect(getByText(/hello there i am a test/)).toBeTruthy()
      10 |     })
      11 |     it('matches the snapshot', () => {

      at Object.it (src/components/Button/test.tsx:8:44)

  ● <Button> › matches the snapshot

    ReferenceError: React is not defined

      10 |     })
      11 |     it('matches the snapshot', () => {
    > 12 |         const { container } = customRender(<Button />)
         |                                            ^
      13 |         expect(container.firstChild).toMatchSnapshot()
      14 |     })
      15 | })

      at Object.it (src/components/Button/test.tsx:12:44)

Button.test.tsx:

import React from 'react'
import Button from '.'
import { customRender } from '../../test-utils'

describe('<Button>', () => {
    it('renders text correctly', () => {
        const text = 'hello there i am a test'
        const { getByText } = customRender(<Button>{text}</Button>)
        expect(getByText(/hello there i am a test/)).toBeTruthy()
    })
    it('matches the snapshot', () => {
        const { container } = customRender(<Button />)
        expect(container.firstChild).toMatchSnapshot()
    })
})

还使用 React 导入,例如将其从第 1 行移到第 3 行似乎有时会使测试通过。这很奇怪。

【问题讨论】:

  • import Button from '.' 是做什么的?
  • 这是 VSCode 的自动导入。它是从索引导入的。所以import Button from './index'.
  • 如果我使用import Button from './index' 它实际上修复了这个测试,但其他测试会中断。我似乎必须将import React, { useContext} from 'react' 迁移到import React from 'react',然后使用React.useContext 或执行import * as React:/
  • 所以在 CI 上运行测试它通过了。我对 CI 脚本进行了不相关的更改,现在测试再次失败。很奇怪:/

标签: javascript reactjs typescript jestjs create-react-app


【解决方案1】:

这是 this issue 中讨论和解释的 jsx 杂注和情感 10 的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2017-10-09
    • 2019-01-30
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多