Javascript 创建react应用程序测试“;未定义“反应”;

Javascript 创建react应用程序测试“;未定义“反应”;,javascript,reactjs,typescript,jestjs,create-react-app,Javascript,Reactjs,Typescript,Jestjs,Create React App,我正在使用react-scripts@2.1.8与typescript@3.3.3与jest@.23.6.0并且运行我的测试时,它们会以“React is not defined”失败 src/components/Button/test.tsx失败 ● › 正确呈现文本 ReferenceError:未定义React 6 |它('正确呈现文本',()=>{ 7 | const text='您好,我正在测试' >8 | const{getByText}=customRender({text})

我正在使用
react-scripts@2.1.8
typescript@3.3.3
jest@.23.6.0
并且运行我的测试时,它们会以“React is not defined”失败

src/components/Button/test.tsx失败
●  › 正确呈现文本
ReferenceError:未定义React
6 |它('正确呈现文本',()=>{
7 | const text='您好,我正在测试'
>8 | const{getByText}=customRender({text})
|                                            ^
9 | expect(getByText(/hello here i am test/).toBeTruthy()
10 |     })
11 |它('与快照匹配',()=>{
在Object.it(src/components/Button/test.tsx:8:44)
●  › 匹配快照
ReferenceError:未定义React
10 |     })
11 |它('与快照匹配',()=>{
>12 | const{container}=customRender()
|                                            ^
13 | expect(container.firstChild).toMatchSnapshot()
14 |     })
15 | })
在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”导入React
从“”导入按钮
从“../../test-utils”导入{customRender}
描述(“”,()=>{
它('正确呈现文本',()=>{
const text='你好,我是一个测试'
const{getByText}=customRender({text})
expect(getByText(/hello here i am a test/).toBeTruthy()
})
它('与快照匹配',()=>{
const{container}=customRender()
expect(container.firstChild.toMatchSnapshot())
})
})

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

这是jsx pragma和情感10的一个问题,如中所讨论和解释。

从“.”导入按钮的功能是什么。的功能是什么?它是VSCode的自动导入功能。它正在从索引导入。因此,“/index”的
import按钮
。如果我使用“/index”的
import按钮
,它实际上修复了这个测试,但其他测试会中断。我似乎必须将
import-React,{useContext}从'React'
迁移到
import-React-from'React'
,然后使用
React.useContext
或将
import*作为React
:因此,在通过的CI上运行测试。我对CI脚本做了一个无关的更改,现在测试再次失败。非常奇怪:/
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()
    })
})