0

I'm trying to test that a GET request is working correctly for Jest, and I can fetch posts by their ID. Please bear with me, I'm very new to front-end testing and not fully sure about how to go about this.

This is my GET request:

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

I'm not fully sure how to test this, as there aren't many examples online about this.

So far, my Jest test looks like this:

import Post from '@/views/Posts.vue'
import { shallowMount } from '@vue/test-utils';


const axios = require('axios');
jest.mock('axios');

jest.mock('@/common.js', () => {
    return{
        baseURL: 'http://localhost:8080/api',
        request: jest.fn().mockResolvedValue({
            data: [
                {   
                    postTitle: null,
                    postContents: null, 
                    ranking: 3, 
                    createdTime: '2021-04-05', 
                    modifiedTime: null, 
                    subforum: 'test', 
                    user: 'tester',
                    comments: ['render? i dont know her']
                }
            ]
        }),
    }
});


describe('test get Post Title', () => {
    afterEach(() => jest.resetAllMocks());
    it('fetches post by post id', async () => {
        const post = await getPost();
        expect(axios.request).toHaveBeenCalledWith({ method: 'get', url: '/posts/${this.$cookie.get('postid')}' });
    });
});

Sorry if this is an extremely stupid question, I'm just quite confused.

ckyzm
  • 1
  • 1
  • Are you getting any errors? I'm guessing `this.$cookie` is `undefined` in your tests. – tao Mar 28 '21 at 00:38
  • error: Parsing error: Unexpected token, expected "," 37 | it('fetches post by post id', async () => { 38 | const post = await getPost(); > 39 | expect(axios.request).toHaveBeenCalledWith({ method: 'get', url: '/posts/${this.$cookie.get('postid')}' }); | ^ This is the error I'm getting! How would I fix the 'this.$cookie' issue? – ckyzm Mar 28 '21 at 00:45
  • You don't. Unit tests should only test that unit and nothing else. You don't want to test `axios` or `vue-cookie` or the browser or some distant API. You only want to test your component. Test that your component is requesting the right stuff from where it should. Test that it handles the response correctly when it gets it. Test that it handles failures correctly when it gets them. You want to test your component against all possible inputs, making sure it outputs/behaves as intended. In short, don't test the world. Test your stuff. – tao Mar 28 '21 at 00:59
  • In your case, you should test if the component is making the call to `getPost()`. You do that by replacing `getPost()` with a mock. First test with a mock that's returning the expected result and make sure the component handles the response correctly. Then, also test with a mock that throws an error and/or with one that returns a malformed result. Make sure your component does what you expect it to in those cases. And you're done. – tao Mar 28 '21 at 01:06
  • Hi there! Thank you for this, I've been trying to follow your instructions and so far, I've come up with jest.mock('axios'); test('should fetch post', () => { const posts = [{Post: 1}]; const resp = {data: posts}; axios.mockResolvedValue(resp); expect(axios.getPost()).toHaveBeenCalledWith({ method: 'get', url: '/posts/postid' }); }); – ckyzm Mar 28 '21 at 19:52
  • I'm getting an error that TypeError: _axios.default.getPost is not a function, and I'm not really sure if i'm going about this the right way? Thank you so much for your help, it's been really helpful. – ckyzm Mar 28 '21 at 19:53

0 Answers0