有没有办法从 jest spyOn mockImplementation 中访问这个(当前实例)?
Is there a way to access this (current instance) from within jest spyOn mockImplementation?
在我的测试套件中,我执行了以下操作来模拟 class 方法:
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"
)
);
});
});
有没有办法从这个模拟中引用当前 class 实例?
箭头函数 () => {}
从它们的声明范围中捕获 this
的值。所以要替换一个原型方法,你需要使用一个function
语句。
另外,Typescript 需要提示 this
应该是什么,所以你可以为 this
.
设置一个类型
我认为这应该符合您的期望:
jest
.spyOn(MyClass.prototype, 'loadVars')
.mockImplementation(function (this: MyClass) {
console.log(this.prefix) // works
})
在我的测试套件中,我执行了以下操作来模拟 class 方法:
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"
)
);
});
});
有没有办法从这个模拟中引用当前 class 实例?
箭头函数 () => {}
从它们的声明范围中捕获 this
的值。所以要替换一个原型方法,你需要使用一个function
语句。
另外,Typescript 需要提示 this
应该是什么,所以你可以为 this
.
我认为这应该符合您的期望:
jest
.spyOn(MyClass.prototype, 'loadVars')
.mockImplementation(function (this: MyClass) {
console.log(this.prefix) // works
})