5 May 2017

If you use full render not shallow in your tests, your tests might be rendered before the actual component and its subcomponents are fully loaded. In that case you need to delay the output, while enzyme is great, it will sometimes still do the snapshot comparison too early. We need to add an event so the snapshot will be after all the events in the que. For this an easy fix is to use "setTimeout".

Source code viewer
  1. import React from 'react';
  2. import { mount } from 'enzyme';
  3. import toJson from 'enzyme-to-json';
  4.  
  5. describe('<MyComponent />', () => {
  6. it('My test that will do the snapshot after full render.', (done) => {
  7. const wrapper = mount(<MyComponent />);
  8.  
  9. setTimeout(() => {
  10. // Use enzyme-to-json for pretty printed snapshot, for easy diff in the future.
  11. expect(toJson(wrapper.render())).toMatchSnapshot();
  12. // Manually call done so the test will wait for the expect above.
  13. done();
  14. }, 1);
  15. });
  16. });
Programming Language: ECMAScript