小编典典

模拟功能时在Jest中进行作用域限定

reactjs

我有一个测试,尝试在两种不同情况下模拟组件。当我使用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

阅读 275

收藏
2020-07-22

共1个答案

小编典典

除非您特别希望该数组在所有测试之间共享,否则应按以下步骤进行设置:

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

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

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

  // tests...
});
2020-07-22