B
B
bormor2020-06-19 09:03:05
JavaScript
bormor, 2020-06-19 09:03:05

How to mock service API in Jest if api().user.getUserName.mockResolvedValueOnce('...') doesn't work?

api().user.getUserName.mockResolvedValueOnce('Alice') call returns
5eec54ef353c9967440062.png

test code error

import MyComponent from '@/views/MyComponent.vue';
import { mount } from '@vue/test-utils';

import api from '@/helpers/api'   
import flushPromises from 'flush-promises'  

jest.mock('@/helpers/api')                    


describe('MyComponent.vue', () => {
  it('calls api with getMessage and show "Username: Alice"', async () =>{
    api().user.getUserName.mockResolvedValueOnce('Alice')    
    const wrapper = mount(ApiServise)
    
    await flushPromises()                          
    
    expect( api().user.getUserName ).toHaveBeenCalledTimes(1) 
    const usernameText = wrapper.find('.username').text()
    expect( usernameText ).toEqual('Username: Alice')
    
  })
});


service code
import axios from 'axios';

const MOCK_SERVER = 'https://reqres.in/api'

const user = {
  getUserName(id = 2) {
    return axios
      .get(`${MOCK_SERVER}/users/${id}`)
      .then(r => r.data)
      .then(r => r.data)
      .then(r => r.first_name)
  }, 
}

export default function api(){
    return {
    user
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question