Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take Snapshot after componentDidMount resolve a promise

  • A componentDidMount call a store that call the api
  • api is a module with export fetchVersionsRequest function
  • fetchVersionsRequest call the api endpoint using Promise
  • all is updated by store after the promise resolved
  • Mobx, via @observer will call component render again because all was updated

Please, check the comments

Home component

@inject('versionStore') @observer
export default class extends Component {
  componentDidMount() {
    const { fetch } = this.props.versionStore;
    fetch(); // Will call api.fetchVersionsRequest
  }

  render() {
    // all is an array updated after call api.fetchVersionsRequest resolved
    const { all } = this.props.versionStore; 
    // ...
    return {all.map(it => <p>{it.name}</p>)}
  }
}

How can I test if component is rendering right?
I want to use Snapshot feature, give a list returned by api, the component should be mach the snapshot

My test Home component

it('renders versions', function() {
  const versions = [
    { id: 1, name: 'version1' },
    { id: 2, name: 'version2' },
  ];

  api.fetchVersionsRequest = jest.fn(() => {
    return Promise.resolve(versions);
  });

  const wrapper = shallow(<Home {...this.minProps} />);
  expect(toJson(wrapper)).toMatchSnapshot(); // PROBLEM Snapshot does not contain any p element
}
like image 774
ridermansb Avatar asked Dec 05 '25 09:12

ridermansb


1 Answers

Just to show you how to work with promises in jest. You have to return the promise from your test to let jest know that it have to wait for it.

it('renders versions', function() {
  const versions = [
    { id: 1, name: 'version1' },
    { id: 2, name: 'version2' },
  ];
  const p = Promise.resolve(versions);
  api.fetchVersionsRequest = jest.fn(() => {
    return p
  });

  const wrapper = shallow(<Home {...this.minProps} />);
  return p.then(()=>{
    expect(toJson(wrapper)).toMatchSnapshot(); 
  })

}

or

it('renders versions', async function() {
  const versions = [
    { id: 1, name: 'version1' },
    { id: 2, name: 'version2' },
  ];
  const p = Promise.resolve(versions);
  api.fetchVersionsRequest = jest.fn(() => {
    return p
  });

  const wrapper = shallow(<Home {...this.minProps} />);
  a
  expect(toJson(wrapper)).toMatchSnapshot(); 

}

It is explained here in the docs

like image 185
Andreas Köberle Avatar answered Dec 07 '25 17:12

Andreas Köberle