首页 > 解决方案 > 有没有办法让 `toHaveBeenCalledWith` 匹配正则表达式?

问题描述

我有一个附加随机数的函数,然后调用另一个函数。我想检查它是否被传入的文本调用并匹配任何随机数。我希望能够在没有 Jest 字面上匹配正则表达式的情况下通过正则表达式。就像是:

 const typeFn = jest.fn();

 function type (text) {
     typeFn(text + Math.random());
 })


 type('hello')
 expect(typeFn).toHaveBeenCalledWith(/hello\d+/)

标签: jestjs

解决方案


您可以使用其中一个辅助函数来expect代替实际值:

expect(typeFn).toHaveBeenCalledWith(expect.stringMatching(/hello\d+/));

这是一个活生生的例子:https ://repl.it/@marzelin/FrighteningCapitalConferences


推荐阅读