【问题标题】:Scoping in Jest when mocking functions模拟函数时 Jest 中的作用域
【发布时间】:2018-04-01 23:45:41
【问题描述】:

我有一个测试,我试图在两种不同的情况下模拟一个组件。当我使用jest.fn。看起来第一个测试只是从第二个测试中获取值。

describe('tests', () => {
  let sampleArray = new Array()
  Array.prototype.test = function() {
    return this.innerArray()
  }
  describe('empty', () => {
    sampleArray.innerArray = jest.fn(() => [])
    it('testArray is empty', () => {
      expect(sampleArray.test().length).toEqual(0)
    })
  })

  describe('not empty', () => {
    sampleArray.innerArray = jest.fn(() => ['test'])
    it('testArray is not empty', () => {
      console.log(sampleArray.innerArray())
      expect(sampleArray.test().length).toEqual(1)
    })
  })
})

当我console.log 时,我从 innerArray 获得了我期望的数组,但它看起来好像没有使用它。

FAIL  test/sample.test.js
  tests
    empty
      ✕ testArray is empty (8ms)
    not empty
      ✓ testArray is not empty (4ms)

  ● tests › empty › testArray is empty

    expect(received).toEqual(expected)

    Expected value to equal:
      0
    Received:
      1

编辑:如果我把它放在it 范围内,它就可以工作。但是为什么我不能在describe 范围内做呢?

describe('tests', () => {
  let sampleArray = new Array()
  Array.prototype.test = function() {
    return this.innerArray()
  }
  describe('empty', () => {
    it('testArray is empty', () => {
      sampleArray.innerArray = jest.fn(() => [])
      console.log(sampleArray.innerArray())
      expect(sampleArray.test().length).toEqual(0)
    })
  })

  describe('not empty', () => {
    it('testArray is not empty', () => {
      sampleArray.innerArray = jest.fn(() => ['test'])
      expect(sampleArray.test().length).toEqual(1)
    })
  })//works

【问题讨论】:

  • 在第一行,第一行,你的意思是const sampleArray = new Array()吗?
  • @LorenzoMarcon 如果没有参数,添加括号并不重要。
  • @Andrew 看起来it 函数是异步的。因此,在运行sampleArray.innerArray = jest.fn(() => []) 之后,并没有运行相应的it 回调,而是运行sampleArray.innerArray = jest.fn(() => ['test']),导致测试用例失败。
  • @Prakashsharma 出色的洞察力。但话虽如此,我该如何解决它,这样我就不必为每个测试用例在 it 内重复相同的 5 行?

标签: javascript reactjs jestjs


【解决方案1】:

除非您特别希望在所有测试之间共享该数组,否则您应该按如下方式设置它:

Array.prototype.test = function() {
  return this.innerArray()
}

describe('tests', () => {
  let sampleArray

  beforeEach(() =>
    sampleArray = new Array()
  })

  // tests...
});

【讨论】:

  • 效果很好!非常感谢。
  • 我也很确定你可以使用 [] 而不是 simpleArray。
  • 在这种情况下,这是真的。但我想对我的实际测试(即函数)进行最接近的复制。
  • 好的,这就解释了奇怪的测试套件。 :)
猜你喜欢
  • 2018-09-14
  • 1970-01-01
  • 2019-01-24
  • 2022-06-29
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
相关资源
最近更新 更多