所以我有一个React类,可以将其称为A。我正在对其进行开玩笑的测试,但是我不断得到
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
在React类中,我正在做:
export class A extends Component ..
在jest测试文件中,我正在执行以下操作:
import { A } from './A.js'
当我跑步时:
const wrapper = mount(<A />)
我收到上面的错误。我在jsdom环境上开玩笑。我有点茫然为什么这行不通。我读过有人默认导出,但是我不明白为什么导入适当的名称不起作用。有谁知道可能是什么问题?
真实代码: 笑话文件:
import Adapter from 'enzyme-adapter-react-16';
import Enzyme, { shallow, mount } from 'enzyme';
import React from 'react';
import { A } from '../A';
Enzyme.configure({ adapter: new Adapter() });
/**
* Test Suite
*/
describe('A test', () => {
it('calls componentDidMount', () => {
const wrapper = mount(<A />);
})
})
反应类:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export class A extends Component {
...
}
最好的配置:
module.exports = {
clearMocks: true,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// The test environment that will be used for testing
testEnvironment: 'jsdom',
testURL: 'http://localhost/',
// Directory to search for tests
roots: ['src/'],
// The glob patterns Jest uses to detect test files
testMatch: [
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[tj]s?(x)'
],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: [
'/node_modules/'
],
snapshotSerializers: [
'enzyme-to-json/serializer'
]
};
答案 0 :(得分:1)
这是您尝试将Object
渲染为Component
时遇到的错误。
这里是一个例子:
A.js
import * as React from 'react';
const AnObject = {}; // <= NOT a component
export class A extends React.Component {
render() {
return (<AnObject/>); // <= Attempt to render an object as a component
}
}
A.test.js
import * as React from 'react';
import { mount } from 'enzyme';
import { A } from './A';
test('A', () => {
const wrapper = mount(<A/>); // <= Fails with "Invariant Violation: Element type...
});
...会出现以下错误:
不变违规:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到了:对象。您可能忘记了从定义文件中导出组件,或者可能混淆了默认导入和命名导入。
检查
A
的呈现方法。
5 |
6 | test('A', () => {
> 7 | const wrapper = mount(<A/>);
| ^
8 | });
9 |
您需要在测试时检查A
,并确保它实际上是您的组件。
然后向后工作,并确保由A
呈现为组件的所有内容实际上都是一个组件(依此类推),直到找到用作组件的非组件为止。
答案 1 :(得分:0)
您无法通过LayoutGroup
调用import { A } from '../A';
,它不会默认导出,因此您不能将其重命名为命名导入。
要做这样的改变
import { A } from './A.js'
到
import A from './A.js'
和
export class LayoutGroup extends Component {
到
export default class LayoutGroup extends Component {