3

I'm using vue2 with composition Api, vuex and apollo client to request a graphql API and I have problems when mocking composable functions with jest

// store-service.ts
export function apolloQueryService(): { 
  
  // do some graphql stuff

  return { result, loading, error };
}

// store-module.ts
import { apolloQueryService } from 'store-service'

export StoreModule {
  state: ()=> ({
    result: {}
  }),
  actions: {
    fetchData({commit}) {
      const { result, loading, error } = apolloQueryService()
      commit('setState', result);
    }
  },
  mutations: {
    setState(state, result): {
      state.result = result
    }
  }
}

The Test:

// store-module.spec.ts
import { StoreModule } from store-module.ts

const store = StoreModule 
describe('store-module.ts', () => {
  beforeEach(() => {
    jest.mock('store-service', () => ({
      apolloQueryService: jest.fn().mockReturnValue({ 
        result: { value: 'foo' }, loading: false, error: {} 
      })
    }))
  })

  test('action', async ()=> {
    const commit = jest.fn();
    await store.actions.fetchData({ commit });
    expect(commit).toHaveBeenCalledWith('setData', { value: 'foo' });
  })
}

The test fails, because the commit gets called with ('setData', { value: undefined }) which is the result from the original apolloQueryService. My Mock doesn't seem to work. Am I doing something wrong? Appreciate any help, thanks!

Haifeng
  • 31
  • 1
  • 2

1 Answers1

0

Try this :

// store-module.spec.ts
import { StoreModule } from store-module.ts

// first mock the module. use the absolute path to store-service.ts from the project root
jest.mock('store-service');

// then you import the mocked module.
import { apolloQueryService } from 'store-service'; 

// finally, you add the mock return values for the mock module
apolloQueryService.mockReturnValue({ 
   result: { value: 'foo' }, loading: false, error: {} 
});

/* if the import order above creates a problem for you,
   you can extract the first step (jest.mock) to an external setup file.
   You should do this if you are supposed to mock it in all tests anyway.
   https://jestjs.io/docs/configuration#setupfiles-array */


const store = StoreModule 
describe('store-module.ts', () => {
  test('action', async ()=> {
    const commit = jest.fn();
    await store.actions.fetchData({ commit });
    expect(commit).toHaveBeenCalledWith('setData', { value: 'foo' });
  })
}
EmirDev
  • 87
  • 5