Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking up static methods in jest

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?

like image 365
Clemens Avatar asked May 19 '18 04:05

Clemens


People also ask

Can static methods be mocked?

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.

How do you mock methods in Jest?

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.

How do you use spyOn function in Jest?

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.


1 Answers

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')     }) }) 
like image 86
Peter Stonham Avatar answered Oct 19 '22 09:10

Peter Stonham