【问题标题】:Jest: Spy on object method?笑话:监视对象方法?
【发布时间】:2020-12-04 22:47:37
【问题描述】:

我需要监视Date.toISOString() 并返回一个值。

const spy = jest.spyOn(global, Date); 间谍全球日期

const spy = jest.spyOn(global, 'get', Date); 间谍全球获取日期

但是你如何监视对象方法呢?并返回一个值?

const spy = jest.spyOn(global.Date, 'toISOString').mockImplementation(() => {
        return new Date().now()
      })

Cannot spy the toISOString property because it is not a function; undefined given instead

const spy = jest.spyOn(global.Date.toISOString).mockImplementation(() => {
        return new Date().now()
      })

Cannot spyOn on a primitive value; undefined given

【问题讨论】:

  • 没有。返回Cannot spy the toISOString property because it is not a function; undefined given instead
  • 没有Date.toISOString()这样的东西。
  • 是的,它是一个实例方法。但是如何存根呢?

标签: javascript testing jestjs spy


【解决方案1】:

想出了解决办法:

const spy = jest.spyOn(global.Date.prototype, 'toISOString').mockImplementation(() => {
        return '123123123'
      })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2021-02-04
    • 2020-01-02
    相关资源
    最近更新 更多