为什么在编写javascript测试时使用beforeach()?

为什么在编写javascript测试时使用beforeach()?,javascript,testing,Javascript,Testing,我正在学习如何为我的代码编写测试,我的指导老师解释了如何将正在呈现的组件放在一个beforeach函数中,如下所示 describe('CommentBox', () => { let component; beforeEach(() => { component = renderComponent(CommentBox); }); it('has the correct class', () => { expect(component).t

我正在学习如何为我的代码编写测试,我的指导老师解释了如何将正在呈现的组件放在一个beforeach函数中,如下所示

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;
  });
});
为什么要在每次使用之前使用。为什么不在descripe函数的顶部声明组件变量呢

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;
  });
});
这似乎可以节省几行额外的代码,减少您必须编写的一个函数?

beforeach在每次测试之前运行。这意味着每个测试都会获得新的数据进行测试

如果您以另一种方式进行测试,则每个测试都可能修改对象,然后在下一个测试中污染对象

最好的做法是不要在测试之间创建依赖关系,这样您就可以更准确地找到bug,或者确保您的测试实际测试了您想要的逻辑

我假设您的测试呈现组件