Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snapshot with router not work

This is different from this one enzyme-to-snapshot-render-object-as-json because

Here I want to generate snapshot with JSON definition of objects
The other I want generate snapshot only for HTML generated by component.


Snapshot tests always fail because the key property in history change every time.

// ComponentContainer.jsx
class ComponentContainer extends Component {
  render() { ... }
}
export { ComponentContainer };    
export default withRouter(ComponentContainer);

And the tests ..

// ComponentContainer.test.jsx
import { ComponentContainer } from './ComponentContainer';

const minProps = {
  history: {
    push: jest.fn(),
  },
};

const wrapped = mount(
  <Router history={minProps.history}>
    <ComponentContainer.wrappedComponent {...mergedProps} {...mergedStores} />
  </Router>,
);

expect(toJson(wrapper)).toMatchSnapshot();

Generate this snapshot ..

// ComponentContainer.test.jsx.snap
<MemoryRouter
    history={
      Object {
        "push": [Function],
      }
    }
  >
    <Router
      history={
        Object {
          "action": "POP",
          "block": [Function],
          "canGo": [Function],
          "createHref": [Function],
          "entries": Array [
            Object {
              "hash": "",
              "key": "mmldr1", // THIS IS GENERATED ON EACH TEST
              "pathname": "/",
              "search": "",
              "state": undefined,
            },
          ],

Attempts

I try to use memory history ...

// ComponentContainer.test.jsx
import createHistory from 'history/createMemoryHistory';

const history = createHistory({
  initialEntries: [`/myapp/123`],
});

<Router history={history}>
  <ComponentContainer.wrappedComponent />
</Router>

But I end up the same problem.

like image 968
ridermansb Avatar asked Oct 29 '25 09:10

ridermansb


1 Answers

You need to use enzyme.find(ComponentContainer) to make a snapshot from the component itself not from the router.

like image 88
Andreas Köberle Avatar answered Oct 31 '25 10:10

Andreas Köberle