Javascript 如何使用Jest测试函数中的函数
我有一些在函数中包含函数的代码,我希望能够对父函数中的函数进行单元测试 我希望有测试,单元测试这些和间谍对他们(这两个要求是必要的) 例如:Javascript 如何使用Jest测试函数中的函数,javascript,jestjs,Javascript,Jestjs,我有一些在函数中包含函数的代码,我希望能够对父函数中的函数进行单元测试 我希望有测试,单元测试这些和间谍对他们(这两个要求是必要的) 例如: export default parentFunction = () => { const innerFunction = () => { //that does stuff } const anotherInnerFunction = () => { //that does more stuff }
export default parentFunction = () => {
const innerFunction = () => {
//that does stuff
}
const anotherInnerFunction = () => {
//that does more stuff
}
//and at some point, the functions are called
//like this
innerFunction()
const anotherFunction = () => {
//or like this
anotherInnerFunction()
}
}
我一直无法找到一种方法来测试这些内部功能。我试过以下方法
示例测试
import parentFunction from "myfile"
it("should call innerFunction", () => {
//this causes an error in jest
const innerFunctionSpy = jest.spyOn(parentFunction, "innerFunction")
//..etc
expect(innerFunctionSpy).toHaveBeenCalled()
})
it("will return a value from anotherInnerFunction", () => {
//this does not work
const value = parentFunction.anotherInnerFunction()
//this also does not work
const value = parentFunction().anotherInnerFunction()
//..etc
})
父函数是否需要重构才能测试这些内部函数?如果我的父函数是一个对象,那么我可以测试这些,但是,我不确定我是否可以重构我的代码来像这样工作
比如说
export default parentFunction = {
innerFunction: () => {
//that does stuff
},
//more code
}
在JavaScript中,您无法访问另一个函数中的变量或函数范围。除非通过从该函数返回它们或从模块导出它们来显式公开它们。这不是开玩笑,这是它在JavaScript中的工作方式
jest.spyOn(parentFunction,“innerFunction”)
上面的代码行表明,innerFunction
函数被设置为parentFunction
对象的属性,但事实并非如此。实际上,innerFunction
是一个作用域位于parentFunction
内部的函数,不能从parentFunction
的范围之外访问。除非您显式返回它或在模块级范围中定义它,然后将其导出
但不应公开此类内部功能的内部工作或实现细节,但如果需要,则应在其名称前使用\uuu
标记为内部工作或实现细节,例如:
//scoped to the module
const _innerFunction = () => {
//that does stuff
}
//scoped to the module
const _anotherInnerFunction = () => {
//that does more stuff
}
//exported as a public API
const anotherFunction = () => {
_anotherInnerFunction()
}
const publicApi = {
anotherFunction,
// expose the private functions for unit tests
_innerFunction,
_anotherInnerFunction
}
export default publicApi;
然后在您的玩笑测试用例中:
import publicApi from "myfile"
it("should call anotherFunction", () => {
const anotherFunctionSpy = jest.spyOn(publicApi, "anotherFunction")
//..etc
expect(anotherFunctionSpy ).toHaveBeenCalled()
})
it("should call _innerFunction", () => {
const innerFunctionSpy = jest.spyOn(publicApi, "_innerFunction")
//..etc
expect(innerFunctionSpy ).toHaveBeenCalled()
})
谢谢你的解释,这很有帮助。看来我有一些重构要做!