0

I am trying to mock a GET request to get some Posts using the ID. This is the code I am trying to mock:

getPost() {
  this.refreshToken();
  http
    .get(`/posts/${this.$cookie.get('postid')}`, {
      headers: {
        "Authorization": `Bearer ${this.$cookie.get('token')}`,
        "Content-type": "application/json",
      },
    })
    .then((response) => {
      this.post = response.data;
    })
    .catch((error) => {
      console.log(error.response);
    });
}

This is my attempt at a test:

import {getPost} from '@/views/Post.vue'
import axios from 'axios';

jest.mock('axios');

describe('get Post by ID', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('should return empty when axios.get failed', async () => {
    const getError = new Error('error');
    axios.get = jest.fn().mockRejectedValue(getError);
    const actualValue = await getPost();
    expect(actualValue).toEqual(new Map());
    expect(axios.get).toBeCalledWith('/posts/postid');
  });

  it('should return users', async () => {
    const mockedUsers = [{ postID: 1 }];
    axios.get = jest.fn().mockResolvedValue(mockedUsers);
    const actualValue = await getPost(['1']);
    expect(actualValue).toEqual(mockedUsers);
    expect(axios.get).toBeCalledWith('/posts/postid');
  });
})

The error I am getting is:

TypeError: (0 , _Post.getPost) is not a function

I am not sure what to do, and any help would be super appreciated. Thanks!

SoyChai
  • 320
  • 2
  • 11
ckyzm
  • 1
  • 1

1 Answers1

0

Assuming you have getPost() defined in the Post component's methods, you can't use named imports to access getPost. Instead, you'll have to mount the component, and use the wrapper's vm:

// Post.spec.js
import { shallowMount } from '@vue/test-utils'
import Post from '@/views/Post.vue'

it('...', () => {
  const wrapper = shallowMount(Post)
  await wrapper.vm.getPost()
  expect(wrapper.vm.post).toEqual(...)
})

Also make sure to return the axios call in getPost() so that it could be awaited:

// Post.vue
export default {
  methods: {
    getPost() {
      this.refreshToken();
        
      return http.get(/*...*/)
        .then(/*...*/)
        .catch(/*...*/);
    }
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307
  • Hi there, thank you so much for this! I've changed it to `it('should return empty when axios.get failed', async () => { const wrapper = shallowMount(Post) await wrapper.vm.getPost() const getError = new Error('error'); axios.get = jest.fn().mockRejectedValue(getError); expect(wrapper.vm.post).toEqual("undefined"); expect(axios.get).toBeCalledWith('/posts/postid'); });` But I am getting an error TypeError: Cannot read property 'get' of undefined. I'm not sure why this is the case? – ckyzm Mar 30 '21 at 22:28