Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Window.postMessage() in JEST?

Tags:

reactjs

jestjs

I have a Window.postMessage() setup in an iFrame to send a message to the host React App. This all workers perfectly but I'm unable to match Expected with Received.

My Test

test('when postMessage is called should emit an event', () => {
  window.top.postMessage = jest.fn();
  const searchString = '?envId=1234';
  window.history.pushState({}, '', `/test${searchString}`);

  const result = '{"error":false,"message":"?envId=1234"}';//, "*"';

  render(<Tree />);
  expect(window.top.postMessage).toHaveBeenCalledTimes(1);
  expect(window.top.postMessage).toHaveBeenCalledWith(result);
});

Result

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: "{\"error\":false,\"message\":\"?envId=1234\"}"
Received: "{\"error\":false,\"message\":\"?envId=1234\"}", "*"

Number of calls: 1

I have also tried: const result = ['{"error":false,"message":"?envId=1234"}','*'];

I can't figure out how to handle the , "*". How can I match with the true result?

like image 419
chris loughnane Avatar asked Oct 28 '25 03:10

chris loughnane


1 Answers

I was thinking about it incorrectly. Changing these lines gives my desired result

  const param1 = {"error":false, "message":searchString}, param2 = "*";

  render(<Tree />);
  expect(window.top.postMessage).toHaveBeenCalledTimes(1);
  expect(window.top.postMessage).toHaveBeenCalledWith(JSON.stringify(param1), param2);
like image 144
chris loughnane Avatar answered Oct 30 '25 17:10

chris loughnane