Home > front end >  Javacript / Jest . Is there a way to add `.toMatchSnapshot` for each `it` test?
Javacript / Jest . Is there a way to add `.toMatchSnapshot` for each `it` test?

Time:08-12

Is there a way to add .toMatchSnapshot for each it test? If I have a lot of tests like that

describe('components/Footer.tsx', () => {
  it('renders a Footer', () => {
    const { asFragment } = render(
      <MemoryRouter>
        <Footer />
      </MemoryRouter>,
    )
    expect(asFragment()).toMatchSnapshot()
  })
  it('renders a Component2', () => {
   
  })
  it('renders a Component3', () => {
   
  })
  ...
  it('renders a ComponentX', () => {
   
  })
})

CodePudding user response:

You could use an utility function for that.


const testComponentRenders = (name, component) => {
  it(`renders ${name}`, () => {
    const { asFragment } = render(component);
    expect(asFragment()).toMatchSnapshot();
  });
}


describe('components/Footer.tsx', () => {

  ;[
    { 
      name: 'footer', 
      component: (
        <MemoryRouter>
          <Footer />
        </MemoryRouter>
      )
    },
    {
      name: 'component1',
      component: <component1 />
    },
    ...
  ].forEach(testCase => testComponentRenders(testCase.name, testCase.component));

});

  • Related