首页 > 解决方案 > 如何使用 Enzyme 和 Jest 创建组件的浅渲染?

问题描述

我正在尝试尽我所能遵循使用 Enzyme 和 Jest 创建浅层渲染的文档,但我似乎遗漏了一些东西。这是我的组件。


class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      code: ""
    }
  }

  getCode() {
    return "7";
  }

  render() {
    return (
      <div></div>
    );
  }
}

export default Example;

当我在浅层渲染上调用 getCode() 时,我希望得到“7”,但渲染是未定义的。

这是我的测试用例:

import Example from './Example'
import { shallow } from 'enzyme';

it('gets a code from example', () => {
  const component = shallow(<Example />);
  console.log(JSON.stringify(component));

  expect(component.getCode().toEqual('7'));
});

我的输出:

 FAIL  src/components/CreateGame/Example.test.js (8.116s)
  ● Console

    console.log src/components/CreateGame/Example.test.js:7
      {}

  ● gets a code from example

    TypeError: component.getCode is not a function

       7 |   console.log(JSON.stringify(component));
       8 |
    >  9 |   expect(component.getCode().toEqual('7'));
         |                    ^
      10 | });

      at Object.<anonymous> (src/components/CreateGame/Example.test.js:9:20)

我觉得我可能在这里遗漏了一些小东西,但对于我的生活,我无法弄清楚它是什么。

标签: reactjsenzyme

解决方案


如果getCode是组件内的方法,则必须获取instance

import Example from './Example'
import { shallow } from 'enzyme';

it('gets a code from example', () => {
  const component = shallow(<Example />);
  const instance = component.instance(); // This is missing

  expect(instance.getCode().toEqual('7'));
});

推荐阅读