开玩笑地嘲笑静态方法 [英] Mocking up static methods in jest

查看:69
本文介绍了开玩笑地嘲笑静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在嘲笑一个静态方法时遇到麻烦.假设您有一个带有静态方法的A类:

I am having trouble mocking up a static method in jest. Immagine you have a class A with a static method:

export default class A {
  f() {
    return 'a.f()'
  }

  static staticF () {
    return 'A.staticF()'
  }
}

和导入A的B类

import A from './a'

export default class B {
  g() {
    const a = new A()
    return a.f()  
  }

  gCallsStaticF() {
    return A.staticF()
  }
}

现在您要模拟A.很容易模拟f():

Now you want to mock up A. It is easy to mock up f():

import A from '../src/a'
import B from '../src/b'

jest.mock('../src/a', () => {
  return jest.fn().mockImplementation(() => {
    return { f: () => { return 'mockedA.f()'} }
  })
})

describe('Wallet', () => {
  it('should work', () => {
    const b = new B()
    const result = b.g()
    console.log(result) // prints 'mockedA.f()'
  })
})

但是,我找不到有关如何模拟A.staticF的任何文档.这可能吗?

However, I could not find any documentation on how to mock up A.staticF. Is this possible?

推荐答案

您可以将模拟对象分配给静态方法

You can just assign the mock to the static method

import A from '../src/a'
import B from '../src/b'

jest.mock('../src/a')

describe('Wallet', () => {
    it('should work', () => {
        const mockStaticF = jest.fn().mockReturnValue('worked')

        A.staticF = mockStaticF

        const b = new B()

        const result = b.gCallsStaticF()
        expect(result).toEqual('worked')
    })
})

这篇关于开玩笑地嘲笑静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆