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?
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",
},
Yes, it should be possible. I wrote the following test and it passed:
test("Test", () => {
var createChatRoomMock = jest.fn();
createChatRoomMock({
"chatRoomUuid": "chatRoom_sZ9nj4hC46e4bGz4PjYzpC",
"creatorId": "user_nCQsasvYirUwwoEr3j8HsC"
});
expect(createChatRoomMock).toHaveBeenCalledWith({
creatorId: expect.stringContaining("user_"),
chatRoomUuid: expect.stringContaining("chatRoom_"),
});
});
The only things I could suggest are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With