mzgoddard / preact-render-spy

Render preact components with access to the produced virtual dom for testing.

Home Page:https://www.npmjs.com/package/preact-render-spy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How would you test componentWillUnmount ?

dmail opened this issue · comments

Hello,

I'm trying preact-render-spy and it does the job very well, thank you for your work.
Right now I'm wondering how would you execute and test code inside a componentWillUnmount method ?

Sorry I apparently had notification off... There is a context.render() method that you could pass a second block of jsx without your component too and it should do an unmount

Can you give me an example of your componentWillUnmount also?

If you want to test some side effect within the dom, there is always context.fragment which will give you the document fragment that was rendered.

Here's an example I cooked up that works:

import { h, Component } from 'preact';
import { shallow } from 'preact-render-spy';

class Unmount extends Component {
  componentWillUnmount() {
    this.props.onUnmount(this);
  }
  
  render() {
    return <div>Unmount me</div>;
  }
}

it('triggers unmount', () => {
  const trigger = jest.fn();
  const context = shallow(<Unmount onUnmount={trigger} />);
  expect(trigger).not.toHaveBeenCalled();

  // This will trigger the componentWillUnmount
  context.render(null);
  expect(trigger).toHaveBeenCalled();
});

I think this makes quite a bit of sense to include in the tests suite, as well as the examples in the README possibly.

Hello @gnarf,

Thank you very much for your response that's exactly what I needed.
My use case test side effect of componentWillUnmount so triggering it is enough 👍
I hope we can keep it that simple with more complex component. I'll let you know if it scales well.

I agree that other people may be happy to find this in the documentation :)