Search code examples
javascriptreactjsunit-testingjestjsts-jest

Mock external library call using jest


New to jest and react code testing. I am testing a file which imports base64 from react-native-base64 and decodes a value that is fetched from backend system in useEffect. Below is the sample code.

import base64 from "react-native-base64";
 
  const xyzWork = async () => {
    const value = await - fetch data from backend
    const decodedValue = base64.decode(value);
    ...
    ...
    ...
  }

  useEffect(() => {
    xyzWork();
  }, []);


  return <div><SomeComponent /></div>;

I am facing difficulties while testing this code using jest. I tried multiple ways to test the same but it is failing with multiple errors.

Some of the ways, import base64 same way and mock like this. base64.decode = jest.fn(()=> "testParsedValue");

Tried to mock entire library itself like const mockedLib = jest.mock("react-native-base64", () => jest.fn()); and then mock base64 of that variable but nothing seems working.

Any help would be appreciated! Thanks!


Solution

  • You can mock it using the Jest module factory e.g.

    jest.mock('react-native-base64', () => ({
        decode: () => "testParsedValue"
    }));