简体   繁体   中英

Why use beforeEach() when writing javascript tests?

I'm learning how to write tests for my code and my instructor explained to put the component being rendered in a beforeEach() function like this...

describe('CommentBox', () => {
  let component;

  beforeEach(() => {
    component = renderComponent(CommentBox);
  });

  it('has the correct class', () => {
    expect(component).to.have.class('comment-box');
  });

  it('has a text area', () => {
    expect(component.find('textarea')).to.exist;
  });

  it('has a button', () => {
    expect(component.find('button')).to.exist;
  });
});

Why use beforeEach(). Why not just declare the component variable at the top of the describe function like so...

describe('CommentBox', () => {
  const component = renderComponent(CommentBox);


  it('has the correct class', () => {
    expect(component).to.have.class('comment-box');
  });

  it('has a text area', () => {
    expect(component.find('textarea')).to.exist;
  });

  it('has a button', () => {
    expect(component.find('button')).to.exist;
  });
});

This would seem to save a couple extra lines of code, and one less function you would have to write?

The beforeEach runs before each test. This means that each test gets fresh data to test with.

If you do it the other way each test could modify the object and then taint the object for the next test.

Its good practice to not create dependencies between tests so that you can more accurately find bugs or ensure your test actually tests the logic you intended.

I assume that your testing renderComponent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM