开玩笑地反应测试,酶表现异常

React tests with jest, enzyme behave strangely

我正在设置单元测试以使用 Jest 和酶测试 React 组件。不知何故,我的设置工作起来很奇怪。当被测组件在测试文件中时,一切正常,但当它被导入时,却没有。

wrapper.debug() 只是输出作为输入给 mount() 的内容,而不是返回组件应该呈现的 JSX。

我的测试组件(TestComponent.js)

import React from 'react';

export default class TestComponent extends React.Component {
  render() {
    return (
      <div>Hello</div>
    )
  }
}

我的规格文件

import React from 'react';
import {mount, shallow} from 'enzyme';

import TestComponent from '../TestComponent';

test('should test my test component',  () => {
  const wrapper = global.mount(<TestComponent />);
  console.log("console print:",wrapper.debug());
  expect(wrapper.find('div').length).toEqual(1);
});

测试失败,收到的值为 0,期望值:1 console.log 打印:

console print: 

<TestComponent />

如果我在测试文件中包含 TestComponent,一切正常。

带有 TestComponet 的 Myspec 文件:

import React from 'react';
import {mount, shallow} from 'enzyme';

export default class TestComponent extends React.Component {
  render() {
    return (
      <div>Hello</div>
    )
  }
}

test('should test my test component',  () => {
  const wrapper = global.mount(<TestComponent />);
  console.log("console print:",wrapper.debug());
  expect(wrapper.find('div').length).toEqual(1);
});

测试通过。

console.log 打印: 控制台打印:

    <TestComponent>
        <div>
            Hello
        </div>
    </TestComponent>

什么是输出:

import TestComponent from '../TestComponent';
console.log(TestComponent);`

?

它必须与在同一文件中声明的第二个位置相同:

class TestComponent extends React.Component {
  render() {
    ...
  }
}
console.log(TestComponent);`

如果它未定义或不等于检查你真正导入的是什么。可能有些导入与文件名或语法混淆。

编辑:问题作者通过在 package.json 中禁用 automock jest 值(在评论中)解决了问题。