Home > Blockchain >  React Test prop component is not called with async
React Test prop component is not called with async

Time:02-26

I have a problem with a test in React.JS. My component scans a QR Code Image, I use this dependency: https://www.npmjs.com/package/qr-scanner with version 1.4.1

This is my test

describe("BarcodeScanner", () => {
  it("can scan qr code image", async () => {
    const handleOnScan = jest.fn();

    render(<BarcodeScanner image={image} onScan={handleOnScan} />);

    expect(await handleOnScan).toHaveBeenCalled();
  });
});

I pass prop image which is an image with qr code, and I pass onScan which is a function of the jest. This function must be called after scanning an image.

This is my Component:

const scanImage = (image: string) => {
  QrScanner.scanImage(image,{
    returnDetailedScanResult: true
  })
  .then((result) => {
    onScan(result.data);
  })
  .catch((error) => {
    if (onError) {
      one rror(error || "No QR code found");
    }
  });
};

My test is not passing because the jest function is not be calling. Test result

CodePudding user response:

You have an incorrect mock for onScan and you are not waiting for results. The action is resolved in the next "tick" not instantly. I think this should work (not tested)

describe('BarcodeScanner', () => {
  it('can scan qr code', async () => {
    const handleOnScan = jest.fn();

    render(<BarcodeScanner image={image} onScan={handleOnScan} />);

    await waitFor(() => expect(handleOnScan).toHaveBeenCalled());
  });
});
  • Related