【问题标题】:How do I mock a native javascript method with Jest?如何使用 Jest 模拟原生 javascript 方法?
【发布时间】:2018-05-08 12:41:52
【问题描述】:

例如,我想测试 JSON.stringify 在测试中被调用 X 次。我可以用 Jest 做到这一点吗?如果有,怎么做?

【问题讨论】:

    标签: javascript unit-testing mocking jestjs


    【解决方案1】:

    您可以使用spyOn 监视本机方法

    const spy = jest.spyOn(JSON, 'stringify')
    console.log(JSON.stringify([{}]))
    console.log(JSON.stringify([{}]))
    expect(spy).toHaveBeenCalledTimes(2)
    

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2017-05-18
      • 2021-12-08
      相关资源
      最近更新 更多