有没有办法用 Jest 模拟私有函数? [英] Is there any way to mock private functions with Jest?

查看:49
本文介绍了有没有办法用 Jest 模拟私有函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要测试的 ES6 模块如下所示:

The ES6 module that I want to test looks as follows:

function privateFunction() {
   ...
}
export function publicFunction() {
   ... does something ...
   privateFunction()
   ... does something else ...
}

我正在使用 JEST 进行单元测试,我试图找到一种方法来测试 publicFunction 并通过模拟它来避免执行 privateFunction,但我无法在模拟尝试中成功.有什么想法吗?

I am using JEST for my unit tests and I am trying to find a way to test publicFunction and avoiding the execution of privateFunction by mocking it but I couldn't succeed in the mock attempt. Any idea?

推荐答案

我找到了一种使用 babel-plugin-rewire 模块来模拟我的私有函数的方法.

I found out a way to mock my private function by using the babel-plugin-rewire module.

package.json 中,我有以下内容:

In package.json I have the following:

  "devDependencies": {
    ...
    "babel-plugin-rewire": "1.0.0-beta-5",
    "babel-jest": "18.0.0",
    ...

.babel.rc 中,我有以下内容:

In .babel.rc I have the following:

{
  "presets": [
    "es2015",
    "stage-0",
    "react"
  ],
  "env": {
    "test": {
      "plugins": [
        "babel-plugin-rewire"
      ]
    }
  },
  ...

此时我可以模拟私有函数:

At this point I was able to mock the private function:

import * as moduleToTest from './moduleToTest.js'

describe('#publicFunction', () => {
  it('mocks private function', () => {
    moduleToTest.__Rewire__('privateFunction', () => { console.log('I am the mocked private function') })
    ...
  })
})

这篇关于有没有办法用 Jest 模拟私有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆