javascript - 模拟函数时在 Jest 中确定范围

标签 javascript reactjs jestjs

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

最佳答案

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

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

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

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

  // tests...
});

关于javascript - 模拟函数时在 Jest 中确定范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46855281/

相关文章:

javascript - 运行 react 测试时出错 : Enzyme, Jest 和 React

reactjs - 布局路线无法按预期使用react-router-dom@6

javascript - 如何在超测失败时打印请求日志(如请求 url、请求正文、请求 queryParam)?

reactjs - 测试使用 try/catch 并调用 Image.getSize 的 React Native 组件的函数

php - 如何在 php/codeigniter 中为日期选择器执行 $_POST

javascript - ReactJs 不存在授权 header

javascript - 为什么在 JavaScript 中为实例变量声明原型(prototype)属性

javascript - 只有第一个调用适用于具有相同顶点缓冲区的多个drawElements调用

javascript - React 中的 JSON 解析嵌套对象

reactjs - 如何使用react-testing-library测试 anchor 的href