Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a function that returns base 64 string

I have a vue component that has a function:

...
reader.onload = () => {
    let base64String = btoa(reader.result);
  };
...

The base64 string is from a file input using a FileReader. I need to pass the base 64 string to the API but on a test with jest, how can I mock reader.onLoad() to return just a simples base64 string?

Thanks.

like image 473
AjjjHsh Avatar asked Aug 08 '26 11:08

AjjjHsh


1 Answers

On a high level, you can try to move the base64String extraction to its own function, then mock that function:

reader.getBase64String = () => {
  return btoa(reader.result)
}

reader.onload = () => {
  let base64String = reader.getBase64String()
  // rest of implementation
};

Then, in your test (this is pseudo-code, might not compile):

MyTestReader extends Reader {
  this.getBase64String = () => {
    return "SSBsaWtlIHRvIExPTAo="
  }
}
like image 84
robert Avatar answered Aug 11 '26 00:08

robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!