0

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) {
      onError(error || "No QR code found");
    }
  });
};

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

1 Answer 1

1

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());
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, Mateusz. I tryied with waitFor, but not is working for me. I have not calls to handleOnScan :( imgur.com/rXsjIsa
There seems to be another problem, but this solves the issue, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.