我有课
export class Player {
constructor() {}
play = async (soundUrl: any) => {
const { sound } = await Audio.Sound.createAsync(soundUrl);
await sound.playAsync();
};
faillure = () => {
this.play(testFailedSound);
};
success = () => {
this.play(successSound);
};
exerciceSuccess = () => {
this.play(exerciceSuccess);
};
}
当我尝试用间谍On模拟成功方法时
const successSoundSpy = jest.spyOn(Player.prototype, "success");
我收到错误消息
Property 'success' does not exist in the provided object
我花了至少 3 个小时试图找出为什么我的代码不起作用,结果发现问题在于我如何定义成功函数。 我最初使用箭头函数:
success = () => {
this.play(successSound);
};
但是这种方法没有将 this 正确绑定到类实例,导致在尝试调用类方法时出现问题。
修复方法是将函数更改为标准方法:
success(){
this.play(successSound);
};
这正确地将 this 绑定到类实例,解决了问题。