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?
Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.
The simplest and most common way of creating a mock is jest. fn() method. If no implementation is provided, it will return the undefined value. There is plenty of helpful methods on returned Jest mock to control its input, output and implementation.
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
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') }) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With