【问题标题】:Javacript / Jest . Is there a way to add `.toMatchSnapshot` for each `it` test?Javascript / 笑话。有没有办法为每个“it”测试添加“.toMatchSnapshot”?
【发布时间】:2022-08-11 00:35:43
【问题描述】:

有没有办法为每个it 测试添加.toMatchSnapshot? 如果我有很多这样的测试

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\', () => {
   
  })
})

    标签: javascript unit-testing jestjs


    【解决方案1】:

    您可以为此使用实用程序函数。

    
    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));
    
    });
    
    

    【讨论】:

    • 我想到了类似afterEach(() =&gt; { callSnapshotTest() })
    猜你喜欢
    • 2012-07-29
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2017-04-09
    • 2015-08-09
    • 2023-01-13
    • 2011-11-26
    • 2017-09-29
    相关资源
    最近更新 更多