当前位置: 首页 > 面试题库 >

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

杜砚
2023-03-14
问题内容

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


 类似资料:
  • 我想对我的服务进行单元测试。在我的服务中,我有一个构造函数,它是: ContractService.ts 我的模型看起来是这样的:(模型是来自sequelize-typescript的类) 所以我想用JEST创建我的单元测试。当我试图模仿contractModel时,它找不到方法,即使我试图模仿它。 我在想,怎样才是嘲弄这个合同模型的正确方法。

  • 我有一个文件,其中包含以下几个helper函数,这些函数在不同的组件中使用。 下面是一个组件,它使用了文件中定义的函数。我正在为组件编写测试,我想模拟这里调用的外部函数。 我对jest/enzyze是新手,我不知道如何模拟外部函数buildoptions。我不知道如何模拟外部的buildOptions功能。有人能帮我做这个吗。下面是我的测试代码:

  • 问题内容: 如何在MySQL中的此表上做滞后处理以打印引号中的差异,例如: 问题答案: 这是我最喜欢的MySQL hack。 这是模拟滞后函数的方式: 保存上一行报价的值。对于第一行,@ quot是-1。 保留当前行的报价的值。 笔记: 子句在这里很重要,就像在常规窗口函数中一样。 您可能还想使用lag 来确保计算相同引号的差异。 您也可以以相同的方式实现行计数器 与该方案相比,与使用聚合函数,存

  • 问题内容: 我正在通过编写一个小型个人项目来学习Go。即使很小,我还是决定从头开始进行严格的单元测试,以学习Go的良好习惯。 琐碎的单元测试都很好而且花哨的,但是我现在对依赖项感到困惑;我希望能够用模拟函数替换一些函数调用。这是我的代码片段: 我希望能够测试downloader()而不实际通过http获取页面- 即通过模拟get_page(更容易使用,因为它仅将页面内容作为字符串返回)或http.

  • 本文向大家介绍Vue使用json-server进行后端数据模拟功能,包括了Vue使用json-server进行后端数据模拟功能的使用技巧和注意事项,需要的朋友参考一下 正开发过程中 前后端分离或者不分离 ,接口多半是之后与页面的开发 ,所以建立rest的APL的接口 给前端提供虚拟的数据是非常必要的 所以这里我使用了json-server作为工具,支持CORS和JSONP跨域请求,支持GET, P

  • null 如上所示,它导出了一些命名函数,而且重要的是 使用了 。 开玩笑地说,当我为 编写单元测试时,我希望模拟 函数,因为我不希望 中的错误影响我为 编写的单元测试。我的问题是我不确定最好的方法是: 如有任何帮助/洞察力,我们将不胜感激。