Jest/Enzyme ShallowWrapper is empty when creating Snapshot

前端 未结 8 838
醉话见心
醉话见心 2020-12-28 15:25

So I\'m writing a test for my Item component and I tried to render the ItemCard component and then use that wrapper to create a snapshot but it returns an empty

相关标签:
8条回答
  • 2020-12-28 16:01

    You can just use mount and debug function like this :

    it('Should render Component', () => {
        const wrapper = mount(<Component {...props} />);
        expect(wrapper.debug()).toMatchSnapshot();
      });
    
    0 讨论(0)
  • 2020-12-28 16:02

    Perhaps a bit late, but i managed to get a solution of this problem by using https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/getElement.html

    describe("Button", () => {
      it("should render basic button correctly", () => {
        const tree = shallow(<Button></Button>);
        expect(tree.getElement()).toMatchSnapshot();
      });
    });
    

    this work on Jest 26.5.3 and enzyme 3.10.5

    0 讨论(0)
  • 2020-12-28 16:05

    You need to use jest-enzyme like:

    https://github.com/airbnb/enzyme/issues/1533#issuecomment-479591007

    0 讨论(0)
  • 2020-12-28 16:09

    I faced the same issue after updating to jest@24.0.0 I have reverted to the previous version jest@23.6.0 for the time being till i figure out what has changed. If you find what has changed, do post it here.

    0 讨论(0)
  • 2020-12-28 16:15

    There shouldn't be a need of reverting version. Following the official DOC

    You need to add this to your Jest configuration:

    "snapshotSerializers": ["enzyme-to-json/serializer"]
    

    clue: could be as easy as add it to your package.json, like:

    {
      "name": "my-project",
      "jest": {
        "snapshotSerializers": ["enzyme-to-json/serializer"]
      }
    }
    

    Sorry if it wasn't the answer. I just saw no-one told it here and it must help other losts like me few minutes ago.

    0 讨论(0)
  • 2020-12-28 16:16

    I faced the same issue and resolved using serializer https://github.com/adriantoine/enzyme-to-json.

    npm install --save-dev enzyme-to-json

    Once installed the enzyme-to-json we can use something like below

    import React, {Component} from 'react';
    import {shallow} from 'enzyme';
    import toJson from 'enzyme-to-json';
    
    it('renders correctly', () => {
      const wrapper = shallow(
        <MyComponent className="my-component">
          <strong>Hello World!</strong>
        </MyComponent>,
      );
    
      expect(toJson(wrapper)).toMatchSnapshot();
    });
    
    

    The same can be resolved using shallow().debug() but prefer to use the above method.

    0 讨论(0)
提交回复
热议问题