为什么jest.fnmockImplementation在beforeEach范围中声明时看不到reset变量?

如何解决为什么jest.fnmockImplementation在beforeEach范围中声明时看不到reset变量?

给出被测模块sut.js

const { dependencyFunc } = require('./dep')

module.exports = () => {
  return dependencyFunc()
}

具有依赖性dep.js

module.exports = {
  dependencyFunc: () => 'we have hit the dependency'
}

和一些测试:

describe('mocking in beforeEach',() => {
  let sut
  let describeScope

  beforeEach(() => {
    let beforeEachScope = false
    describeScope = false

    console.log('running before each',{ beforeEachScope,describeScope })
    jest.setMock('./dep',{
      dependencyFunc: jest.fn().mockImplementation(() => {
        const returnable = { beforeEachScope,describeScope }
        beforeEachScope = true
        describeScope = true
        return returnable
      })
    })
    sut = require('./sut')
  })

  it('first test',() => {
    console.log(sut())
  })

  it('second test',() => {
    console.log(sut())
  })
})

我得到以下输出:

me$ yarn test test.js
yarn run v1.22.5
$ jest test.js
 PASS  ./test.js
  mocking in beforeEach
    ✓ first test (17 ms)
    ✓ second test (2 ms)

  console.log
    running before each { beforeEachScope: false,describeScope: false }

      at Object.<anonymous> (test.js:9:13)

  console.log
    { beforeEachScope: false,describeScope: false }

      at Object.<anonymous> (test.js:22:13)

  console.log
    running before each { beforeEachScope: false,describeScope: false }

      at Object.<anonymous> (test.js:9:13)

  console.log
    { beforeEachScope: true,describeScope: false }

      at Object.<anonymous> (test.js:26:13)

Test Suites: 1 passed,1 total
Tests:       2 passed,2 total
Snapshots:   0 total
Time:        1.248 s,estimated 2 s
Ran all test suites matching /test.js/i.
✨  Done in 3.56s.

我希望两个测试的输出均为{ beforeEachScope: false,describeScope: false }。即,我希望beforeEachScopedescribeScope变量都将重置为false,而不管它们是在beforeEach范围还是describe范围中声明的。在我的真实测试中,我认为将它放在beforeEach范围内比较干净,因为在其他地方不需要它。这是怎么回事?开玩笑的东西使用什么范围?

解决方法

我看起来setMock只考虑了给定模块的第一个模拟,而没有在第二个调用中覆盖它。或更确切地说,我相信是require进行了缓存-笑话在运行整个测试套件之前仅清空模块缓存一次(预计the imports will be at the top of the suite在声明要模拟的模块之后)。

您的模拟实现随后从第一个beforeEachScope调用开始对beforeEach进行了关闭。

为什么您可能会想,为什么describeScope上也没有关闭?实际上,确实如此,可能会使您的代码感到困惑的是,beforeEach确实运行了describeScope = false,这总是将其重置为false,然后再记录到任何地方。如果删除该语句,而仅在let describeScope = false范围内初始化describe,您将看到它在第一次调用true之后也将更改为sut()

如果我们手动解析范围并从执行中删除所有垃圾包装,这就是发生的情况:

let sut
let describeScope

// first test,beforeEach:
let beforeEachScope1 = false
describeScope = false

console.log('running before each 1',{ beforeEachScope1,describeScope }) // false,false as expected
jest.setMock('./dep',{
  dependencyFunc(n) {
    console.log('sut call '+n,describeScope });
    beforeEachScope1 = true
    describeScope = true
  })
})
sut = require('./sut') // will call the function we just created

// first test
sut(1) // still logs false,false

// second test,beforeEach:
let beforeEachScope2 = false // a new variable
describeScope = false // reset from true to false,you shouldn't do this

console.log('running before each 2',{ beforeEachScope2,describeScope }) // logs false,false
jest.setMock('./dep',{
  dependencyFunc(n) {
    // this function is never called
  })
})
sut = require('./sut') // a no-op,sut doesn't change (still calling the first mock)

// second test:
sut(2) // logs true (beforeEachScope1) and false

使用以下内容:

const dependencyFunc = jest.fn();
jest.setMock('./dep',{
  dependencyFunc,})
const sut = require('./sut')

describe('mocking in beforeEach',() => {
  let describeScope = false

  beforeEach(() => {
    let beforeEachScope = false

    console.log('running before each',{ beforeEachScope,describeScope })
    dependencyFunc.mockImplementation(() => {
      const returnable = { beforeEachScope,describeScope }
      beforeEachScope = true
      describeScope = true
      return returnable
    })
  })

  it('first test',() => {
    console.log(sut())
  })

  it('second test',() => {
    console.log(sut())
  })
})

下面的示例演示了缓存和作用域/关闭行为的组合。

let cachedFunction

let varInGlobalClosure

const run = () => {
  varInGlobalClosure = false
  let varInRunClosure = false

  // next line is what jest.mock is doing - caching the function
  cachedFunction = cachedFunction || (() => {
    const returnable = { varInRunClosure,varInGlobalClosure }
    varInRunClosure = true
    varInGlobalClosure = true
    return returnable
  })

  return cachedFunction
}

console.log('first run',run()()) // outputs { varInRunClosure: false,varInGlobalClosure: false }
console.log('second run',run()()) // outputs { varInRunClosure: true,varInGlobalClosure: false }

这是因为我们正在run内创建一个新的闭包,当我们第二次调用varInRunClosure时使用一个新的run,但是缓存的函数仍在使用生成的闭包run第一次运行时,现在在缓存的函数范围之外无法访问。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-