Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()'
  }
}

And a class B that imports A

import A from './a'

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

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

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()'
  })
})

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

question from:https://stackoverflow.com/questions/50421732/mocking-up-static-methods-in-jest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
786 views
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...