本文介绍了模拟函数时在 Jest 中的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a test where I'm trying to mock a component in two different situations. When I use jest.fn. It almost looks like the first test is just taking the value from the second.

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 得到了我期望的数组,但它看起来好像没有使用它.

When I console.log I get the array I expect from innerArray, but it just looks like it doesn't use it.

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

edit:如果我把它放在 it 范围内,它就可以工作.但是为什么我不能在 describe 范围内做到这一点?

edit: If I place it inside the it scope, it works. But why can't I do it in the describe scope?

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

推荐答案

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

Unless you specifically expect the array to be shared among all your tests, you should set it up as follows:

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

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

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

  // tests...
});

这篇关于模拟函数时在 Jest 中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:24