I have a class
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);
};
}
When I try to mock the success method with a spyOn
const successSoundSpy = jest.spyOn(Player.prototype, "success");
I got the error message Property 'success' does not exist in the provided object
I spent at least 3 hours trying to figure out why my code wasn’t working, and it turns out the issue was with how I defined the success function. I initially used an arrow function:
success = () => {
this.play(successSound);
};
But this approach didn’t bind this to the class instance correctly, causing issues when trying to call class methods.
The fix was to change the function to a standard method:
success(){
this.play(successSound);
};
This correctly binds this to the class instance, solving the problem.