javascript - 重复使用具有可选更改的已定义变量

标签 javascript reactjs unit-testing jestjs

我想重用一个在文件开头定义的变量(在我的例子中它是一个测试文件)。 对于某些测试,我必须更改对象的值,但这些更改只应针对此特定测试进行。下一次测试应该再次使用原始对象。

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 block 中创建变量,这样您在每个测试中都有一个干净的实例。特别是因为您不应该在每个测试中重复使用相同的 spy ,因为这很容易隐藏错误的行为。

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

关于javascript - 重复使用具有可选更改的已定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49768799/

相关文章:

android - 从 React Native 中的目录加载一组图像

javascript - SectionList 中的选项卡 React Native

visual-studio - Visual Studio 测试项目

javascript - 使用 BFS 时 N 叉树的最大深度

javascript - 为什么背景图像不使用 Angular 设置?

reactjs - Redux reducer 按名称从列表中删除对象

node.js - Cypress 选择 HTML <select> 的特定子级

unit-testing - 跳过单元测试或至少显示它们的警告

javascript - 纬度/经度数组作为 Google map 上的标记 (API V3)

javascript - 在 javascript 中返回 2 个对象之间的匹配元素数组的最高效方法是什么?