簡體   English   中英

重用已定義的變量並進行可選更改

[英]Reusing a defined variable with optional changes

我想重用一個變量,該變量在文件的開頭定義(在我的情況下是測試文件)。 對於某些測試,我必須更改對象的值,但是這些更改僅應針對此特定測試進行。 下一個測試應再次使用原始對象。

const props = {
  id: 'M1234567890',
  update: jest.fn()
}

describe('example()', () => {
  it('should not call update if id is missing', () => {
    // SETUP
    props.id = undefined
    const component = shallow(<Component {...props} />)
    // EXECUTE
    component.instance().example()
    // VERIFY
    expect(props.update).not.toHaveBeenCalled()
  })
  it('should call update', async () => {
    // SETUP
    const component = shallow(<Component {...props} />)
    // EXECUTE
    await component.instance().example()
    // VERIFY
    expect(props.update).toHaveBeenCalled()
  })
})

我現在正在做的是首先在測試文件的開頭定義“默認”對象( props )。 每個測試都使用此對象。 但是某些測試需要為特定元素獲取不同的值。 在這種情況下,我將設置新值,例如在第一次測試中,將id設置為undefined

但是在第二個測試中,我想再次使用“默認”對象。 在我的代碼中,第二項測試也使用了新的undefined (id)值,但是我需要將原始對象與M1234567890 (id)值一起使用。

最好的方法是在beforeEach塊中創建變量,以便在每個測試中都有一個干凈的實例。 特別是由於您不應在每次測試中重復使用同一間諜,因為這很容易掩蓋錯誤的行為。

describe('example()', () => {
  let props
  beforeEach(()=>{
    props = {
      id: 'M1234567890',
      update: jest.fn()
    }
  })
  it('should not call update if id is missing', () => {
    // SETUP
    props.id = undefined
    const component = shallow(<Component {...props} />)
    // EXECUTE
    component.instance().example()
    // VERIFY
    expect(props.update).not.toHaveBeenCalled()
  })
  it('should call update', async () => {
    // SETUP
    const component = shallow(<Component {...props} />)
    // EXECUTE
    await component.instance().example()
    // VERIFY
    expect(props.update).toHaveBeenCalled()
  })
})

您可以使用Object.assign ,它對您的案例特別有用。

const props = {
  id: 'M1234567890',
  update: jest.fn()
}

describe('example()', () => {
  it('should not call update if id is missing', () => {
    // SETUP
    props.id = undefined
    const component = shallow(<Component {...Object.assign({}, props, {id: undefined})} />)
    // EXECUTE
    component.instance().example()
    // VERIFY
    expect(props.update).not.toHaveBeenCalled()
  })
  it('should call update', async () => {
    // SETUP
    const component = shallow(<Component {...props} />)
    // EXECUTE
    await component.instance().example()
    // VERIFY
    expect(props.update).toHaveBeenCalled()
  })
})

在您要進行更改的任何地方,都可以傳遞要更改的屬性,其余對象將保持不變。

暫無
暫無

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

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