Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

Jest怎么测试非模块函数,又怎么测试未导出的函数?

如果在一个项目中,有一个js,并没有使用export导出函数,那 Jest 该怎么写测试文件?又或者只导出了函数 a,但是函数 b 没有导出,那我不想导出 b 给外部,那怎么写测试函数 b 的测试文件?

// test.js
function test(a,b){
  return a + b
}
(function(){
  test(1,2)
})()
// test.test.js
???

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

听起来 rewire 应该符合你的需求

https://github.com/jhnns/rewire

// test.test.js
const rewire = require('rewire')
const testjs = rewire('test.js')
const testFunction = testjs.__get__('test') // 这是你要测试的函数

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...