Categories
discuss

Can I use `expect.stringContaining()` inside a Jest `.toHaveBeenCalledWith()` block?

Is it possible to use expect.stringContaining() inside a Jest .toHaveBeenCalledWith() block? I am currently using: expect(createChatRoomMock).toHaveBeenCalledWith({ creatorId: expect….

Is it possible to use expect.stringContaining() inside a Jest .toHaveBeenCalledWith() block?

I am currently using:

expect(createChatRoomMock).toHaveBeenCalledWith({
  creatorId: expect.stringContaining("user_"),
  chatRoomUuid: expect.stringContaining("chatRoom_"),
});

But this fails with:

    - Expected
    + Received


    Object {
  -   "chatRoomUuid": StringContaining "chatRoom_",
  -   "creatorId": StringContaining "user_",
  +   "chatRoomUuid": "chatRoom_sZ9nj4hC46e4bGz4PjYzpC",
  +   "creatorId": "user_nCQsasvYirUwwoEr3j8HsC",
    },

This is odd, as you can see from the error, the recieved strings match what’s expected

I’ve also tried:

expect(createChatRoomMock).toHaveBeenCalledWith({
  creatorId: expect.stringMatching(/user_.*/),
  chatRoomUuid: expect.stringMatching(/chatRoom_.*/),
});

With the same results as shown above.

How can I use expect.stringContaining() inside a Jest .toHaveBeenCalledWith() block?

Answer

This is a bug in jest. If there is anything else failing in the test, Jest will show these as failures, even though they would pass, for example:

  it.only("Test", () => {
    var createChatRoomMock = jest.fn();

    createChatRoomMock({
        "chatRoomUuid": "chatRoom_sZ9nj4hC46e4bGz4PjYzpC",
        "creatorId": "user_nCQsasvYirUwwoEr3j8HsC",
        "somethingElse": "bad"
    });

    expect(createChatRoomMock).toHaveBeenCalledWith({
      creatorId: expect.stringContaining("user_"),
      chatRoomUuid: expect.stringContaining("chatRoom_"),
      somethingElse: expect.stringContaining("good")
    });
  });

Will (inaccurately) show that the other .toHaveBeenCalledWith() have failed:

    - Expected
    + Received

      Object {
    -   "chatRoomUuid": StringContaining "chatRoom_",
    -   "creatorId": StringContaining "user_",
    -   "somethingElse": StringContaining "good",
    +   "chatRoomUuid": "chatRoom_sZ9nj4hC46e4bGz4PjYzpC",
    +   "creatorId": "user_nCQsasvYirUwwoEr3j8HsC",
    +   "somethingElse": "bad",
      },
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..