在我的測驗套件上,我做了以下模擬類方法:
beforeEach(() => {
jest
.spyOn(MyClass.prototype, "loadVars")
.mockImplementation(async () => {
const file:string = `MyClass.${
this.prefix // <---- how can I address this?
}.data.mock.json`;
logger.info(`Mocking all parameters from ${file}`);
return JSON.parse(
fs.readFileSync(
process.cwd() `/../data/${file}`,
"utf-8"
)
);
});
});
有沒有辦法從這個模擬中參考當前類實體?
uj5u.com熱心網友回復:
箭頭函式從其宣告范圍() => {}中獲取值。this所以要替換一個原型方法,你需要使用一個function陳述句。
此外,Typescript 需要在此處提示this預期的內容,因此您可以為this.
我認為這應該符合您的期望:
jest
.spyOn(MyClass.prototype, 'loadVars')
.mockImplementation(function (this: MyClass) {
console.log(this.prefix) // works
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419276.html
標籤:
