How to make fun of the React component life cycle method with Jest and Enzyme?

The Enzyme docs for full DOM rendering here contains the following life-cycle espionage example with Sinon:

describe('<Foo />', () => {

  it('calls componentDidMount', () => {
    sinon.spy(Foo.prototype, 'componentDidMount');
    const wrapper = mount(<Foo />);
    expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true);
  });
});

What is equivalent to this using mock functions from Jest?

I use the Create-React-App and prefer not to include Sinon if this can be achieved using Jest.

Here I would expect the test to look like this:

describe('<App />', () => {

  it('calls componentDidMount', () => {
    jest.fn(App.prototype, 'componentDidMount');
    const wrapper = mount(<App />);
    expect(App.prototype.componentDidMount.mock.calls.length).toBe(1);
  });
});

In this case, it App.prototype.componentDidMountdoes not refer to the same function spy as Sinon.

Jest's documentation on how mock functions work is a bit limited. I already discussed here around what jest.fn () does, but it doesn't seem to be equivalent to synon.spy ().

How can I repeat this test using Jest?

+4
2

, jest.fn . , , . Foo , . , , Foo, componentDidMount, . , , .

:

const spy = jest.fn()
const componentDidMount = Foo.prototype.componentDidMount
Foo.prototype.componentDidMount = function(){
  spy()
  componentDidMount()
}
+2

Jest 19 :

describe('<App />', () => {
  it('calls componentDidMount', () => {
    const spy = jest.spyOn(App.prototype, 'componentDidMount');
    const wrapper = mount(<App />);
    expect(spy).toHaveBeenCalled();
    spy.mockReset();
    spy.mockRestore();
  });
});

jest.spyOn mock , mockClear, mockReset mockRestore.

mount create -, .

+1

Source: https://habr.com/ru/post/1665703/


All Articles