无法使用jest模拟组件方法

时间:2017-12-21 08:50:02

标签: jestjs

我想在component中模拟mu jest test方法。

这是指向原始问题的链接:https://github.com/facebook/jest/issues/4696

我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

问题在于该组件在您进行监视之前已呈现,因此onClick已绑定到原始组件。

这是解决方案:

index.tsx

import React, { Component } from 'react';

export default class ToggleCheckbox extends Component {
  constructor(props) {
    super(props);
    this.onChange = this.onChange.bind(this);
  }

  public onChange() {
    console.log('onChange');
  }
  public render() {
    return (
      <div>
        <button onClick={this.onChange}>click</button>{' '}
      </div>
    );
  }
}

index.spec.tsx

import React from 'react';
import ToggleCheckbox from './';
import { shallow } from 'enzyme';

describe('ToggleCheckbox', () => {
  it('spy', () => {
    const spy = jest.spyOn(ToggleCheckbox.prototype, 'onChange').mockImplementation(() => {
      console.log(`spy called`);
    });
    const wrapper = shallow(<ToggleCheckbox />);
    wrapper.find('button').simulate('click');
    expect(spy).toBeCalled();
    spy.mockRestore();
  });
});

单元测试结果:

 PASS  src/stackoverflow/47921226/index.spec.tsx (7.557s)
  ToggleCheckbox
    ✓ spy (19ms)

  console.log src/stackoverflow/47921226/index.spec.tsx:8
    spy called

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.519s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47921226