问题描述
完全错误:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of `LoadableComponent`.
当使用 react-loadable
的组件是被测试组件的子组件并且使用 mount
函数时,会出现此问题。在这种特定情况下,挂载函数来自 material-ui 库的实用程序。
以下是受影响文件的部分:
Parent.jsx
export const Journey = ({
// ... props ...
}) => {
// ... code ...
return (
{/* ... more component ... */}
{(!hasFetchedTopics || isLoading) && (
// component with ComponentUsingReactLoadable as child
<Loading variant={loadingAnimationVariants.secondary} />
)}
{/* ... more component ... */}
)
}
ComponentUsingReactLoadable.jsx
import React from "react"
import Loadable from "react-loadable"
const LottieExt = Loadable({
loader: () =>
import(/* webpackChunkName: "react-lottie-player" */ "react-lottie-player"),loading: () => <CircularProgress color="secondary" size={40} />,})
class Lottie extends React.PureComponent {
// ... component logic ...
return (
{/* ... more component ... */}
<LottieExt
options={options}
width={width}
height={height}
isStopped={isStopped}
{...rest}
/>
{/* ... more component ... */}
)
}
测试/Parent.js
import React from "react"
import createShallow from "@material-ui/core/test-utils/createShallow"
import { createMockStore,createMountWithStore } from "folder/to/helpers"
import Loading from "folder/to/Loading"
import { Parent } from ".."
const mergeProps = newProps => ({
// ...static props ...
...newProps,})
describe("<Journey />",() => {
let store
let mount
let shallow
beforeEach(() => {
shallow = createShallow()
store = createMockStore()
mount = createMountWithStore(store)
})
// ... other tests ...
it("Should show a loader if application is still loading and the topics are already fetched",() => {
const props = mergeProps({
... props ...
})
const component = mount(<Journey {...props} />)
const loader = component.find(Loading)
expect(loader.exists()).toBeTruthy()
})
})
根据参考,我还添加了 createMockStore 和 createMountWithStore
folder/to/helpers.js
export const createMockStore = (slice = {}) =>
configureMockStore(reducerMiddleware)(slice)
/**
* createMountWithStore
* @deprecated
* @alternative you a combination of createWithStore and createMount,examples can be found in the ComponentName tests
* @param {object} store | Slice of the store that you need to test
*/
export const createMountWithStore = store => children =>
createMount()(<Provider store={store}>{children}</Provider>)
我已经按照以下设置在 Jest 的全局设置中添加了 loadable.preloadAll()
个组件:
jestGlobalSetup.js
const loadable = require("react-loadable")
module.exports = async () => {
loadable.preloadAll().then(() => console.log("\n COMPONENTS LOADED"))
}
如果您需要更多信息,请告诉我。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)