What is the purpose of `beforeEach` global in Jest?

前端 未结 2 2062
别那么骄傲
别那么骄傲 2021-02-20 01:19

I always find Jest-Enzyme test cases starting with a beforeEach global that resembles like the following:

describe(\'TEST BLOCK\' () => {
  let w         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-20 01:38

    If you have code that’s common across multiple tests, you can use beforeEach to do some setup before each test runs in order to avoid repetition. In this case, if you have multiple tests that shallow mount Component, you can move the shallow mount to a beforeEach, and the component will be mounted when every test runs. Generally you’ll want to pair this with an afterEach, where you call wrapper.unmount().

    describe('tests', () => {
      it('does one thing', () => {
        const wrapper = shallow();
        // ...test some things
        wrapper.unmount();
      });
    
      it('does another thing', () => {
        const wrapper = shallow();
        // ...test something else
        wrapper.unmount();
      });
    
      it('does a third thing', () => {
        const wrapper = shallow();
        // ...test a third thing
        wrapper.unmount();
      });
    });
    

    becomes:

    describe('tests', () => {
      let wrapper;
    
      beforeEach(() => {
        wrapper = shallow();
      });
    
      afterEach(() => {
        wrapper.unmount();
      });
    
      it('does something', () => {
        // ...test something
      });
    
      it('does something else', () => {
        // ...test something else
      });
    
      it('does another thing', () => {
        // ...test a third something
      });
    });
    

    beforeEach is referred to as the “setup” phase, and afterEach as the “teardown” phase.

    Are we not deliberately slowing down the test runtime?

    No, because you would have to shallow mount the component in each test anyway.

    Isn’t it ok to render it once and assign it to wrapper?

    Persisting a component (or any statefulness) across multiple tests can cause flaky tests, because (for example) you might get a different result if the tests are run in a different order. Any state (such as a mounted component) should be set up before each test and torn down after each test. This makes your tests completely independent from each other.

提交回复
热议问题