[英]How to test functions in a function using Jest
我有一些在函數內部具有函數的代碼,我希望能夠對父函數內部的函數進行單元測試。
我正在尋找對這些進行單元測試並監視它們的測試(這兩個要求都是必需的)。
例子:
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 中另一個函數范圍內的變量或函數。 除非您通過從該函數返回它們或從模塊導出它們來顯式公開它們。 這與 Jest 無關,這是它在 JavaScript 中的工作方式。
jest.spyOn(parentFunction, "innerFunction")
上面的代碼行告訴 Jest, innerFunction
函數被設置為parentFunction
對象的一個屬性,但事實並非如此。 事實上, innerFunction
是一個作用域在parentFunction
內部的parentFunction
,它不能從parentFunction
的作用域之外訪問。 除非您明確返回它或在模塊級別范圍內定義它然后導出它。
但是不應公開此類內部函數的內部工作或實現細節,但如果需要,應在其名稱前使用_
進行標記,例如以下示例:
//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;
然后在你的 Jest 測試用例中:
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()
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.