簡體   English   中英

為什么在編寫JavaScript測試時使用beforeEach()?

[英]Why use beforeEach() when writing javascript tests?

我正在學習如何為我的代碼編寫測試,我的講師解釋了如何將要呈現的組件放在beforeEach()函數中,如下所示...

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

為什么要使用beforeEach()。 為什么不像這樣在聲明函數的頂部聲明組件變量呢?

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

這似乎可以節省幾行額外的代碼行,而您必須編寫的功能少了一些?

beforeEach在每次測試之前運行。 這意味着每個測試都會獲取要測試的新數據。

如果您以其他方式這樣做,則每個測試可以修改對象,然后為下一次測試污染對象。

優良作法是不要在測試之間創建依賴關系,以便您可以更准確地查找錯誤或確保測試實際測試了預期的邏輯。

我假設您正在測試renderComponent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM