有没有办法用Jest模拟私有函数? [英] Is there any way to mock private functions with Jest?
本文介绍了有没有办法用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 <来模拟我的私人功能的方法/ strong>模块。
I found out a way to mock my private function by using the babel-plugin-rewire module.
在 package.json 中,我有以下内容:
"devDependencies": {
...
"babel-plugin-rewire": "1.0.0-beta-5",
"babel-jest": "18.0.0",
...
.babel.rc 我有以下内容:
{
"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屋!
查看全文