如何使用 jest

问题描述

我正在使用带有组合 Api、vuex 和 apollo 客户端的 vue2 来请求 graphql API,并且在使用 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,error } = apolloQueryService()
      commit('setState',result);
    }
  },mutations: {
    setState(state,result): {
      state.result = result
    }
  }
}

测试:

// 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' });
  })
}

测试失败,因为提交被调用 ('setData',{ value: undefined }),这是原始 apolloQueryService 的结果。我的 Mock 似乎不起作用。难道我做错了什么?感谢您的帮助,谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)