功能组件在测试中导入时不起作用

Functional component does not work when importing it in test

我有一个功能组件 Foo.js 如下所示:

const Foo = () => {
  return (
    <View></View>
  )
}
export default Foo

此组件在应用程序中呈现时工作正常


问题是在尝试像这样测试组件时:

import renderer from 'react-test-renderer'
import Foo from './Foo'
test('testing', () => {
  const component = renderer.create(<Foo />)  <--- Error occurs
})

错误发生当运行这个测试(调用renderer.create时),说: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.


奇怪的是测试通过没有任何错误如果我将组件放入测试文件:

const Foo = () => {
  return (
      <View></View>
  )
}
test('testing', () => {
  const component = renderer.create(<Foo />)
})

事实证明,这是因为导出的组件被模拟了,因为我在 jest 配置中将 automock 设置为 true。

jest.config.js 中更改:

automock: true

进入这个:

automock: false

问题已解决。


问题:为什么自动模拟的组件没有返回任何东西?是否可以通过某种方式解决这个问题,以便将 automock 设置为 true 时也能正常工作?