【问题标题】:Is there a way to have `toHaveBeenCalledWith` match a regular expression?有没有办法让 `toHaveBeenCalledWith` 匹配正则表达式?
【发布时间】:2019-02-11 01:04:36
【问题描述】:

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

 const typeFn = jest.fn();

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


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

【问题讨论】:

    标签: jestjs


    【解决方案1】:

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

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

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

    【讨论】:

    • 它有效,谢谢 :) 我只希望有一些看起来更好的东西:祈祷
    猜你喜欢
    • 2011-01-04
    • 2023-03-17
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2013-02-26
    • 2022-12-04
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多