我可以在Jest `.toHaveBeenCalledWith()`块中使用`expect.stringContaining()`吗?

c8ib6hqw  于 2023-09-28  发布在  Jest
关注(0)|答案(3)|浏览(132)

可以在Jest .toHaveBeenCalledWith()块中使用expect.stringContaining()吗?
我目前正在使用:

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

但这失败了:

- Expected
    + Received

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

这很奇怪,从错误中可以看出,收到的字符串与预期的匹配
我也试过:

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

结果与上面所示相同。

如何在Jest .toHaveBeenCalledWith()块中使用expect.stringContaining()

umuewwlo

umuewwlo1#

这是一个bug in jest。如果测试中还有其他失败,Jest will show these as failures, even though they would pass,例如:

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")
    });
  });

将(不准确地)显示其他.toHaveBeenCalledWith()已失败:

- Expected
    + Received

      Object {
    -   "chatRoomUuid": StringContaining "chatRoom_",
    -   "creatorId": StringContaining "user_",
    -   "somethingElse": StringContaining "good",
    +   "chatRoomUuid": "chatRoom_sZ9nj4hC46e4bGz4PjYzpC",
    +   "creatorId": "user_nCQsasvYirUwwoEr3j8HsC",
    +   "somethingElse": "bad",
      },
mjqavswn

mjqavswn2#

是的,应该可以。我写了下面的测试,它通过了:

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

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

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

我唯一能建议的是:

  • 检查输出中的隐藏字符,如Unicode零宽度空格,
  • 如果您使用的不是最新版本的Jest,请尝试更新。我使用的是25.5.2版,在撰写本文时是最新的版本。
tp5buhyn

tp5buhyn3#

我刚刚遇到了这个问题,但解决办法很简单:

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

相关问题