【发布时间】:2019-08-23 19:03:40
【问题描述】:
我将react-scripts@2.1.8 与typescript@3.3.3 与jest@.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