knee-cola / jest-mock-axios

Axios mock for Jest
252 stars 42 forks source link

Axios catch error Request failed with status code 404 #27

Closed priyeshvadhiya closed 5 years ago

priyeshvadhiya commented 5 years ago

i am setting up unit test with jest in my vuejs project.

testing with login component and i have tested successful all the props, input, client validation, but when i test with axios request POST then always return catch error

Error: Request failed with status code 404

console.log node_modules/raven-js/src/console.js:35 { Error: Request failed with status code 404 at createErrorResponse (/Users/artixun/Priyesh/Vue/work/e3-unit-test/node_modules/axios-mock-adapter/src/utils.js:117:15) at Object.settle (/Users/artixun/Priyesh/Vue/work/e3-unit-test/node_modules/axios-mock-adapter/src/utils.js:97:16) at handleRequest (/Users/artixun/Priyesh/Vue/work/e3-unit-test/node_modules/axios-mock-adapter/src/handle_request.js:78:11) at /Users/artixun/Priyesh/Vue/work/e3-unit-test/node_modules/axios-mock-adapter/src/index.js:18:9 at new Promise (<anonymous>) at MockAdapter.<anonymous> (/Users/artixun/Priyesh/Vue/work/e3-unit-test/node_modules/axios-mock-adapter/src/index.js:17:14) at dispatchRequest (/Users/artixun/Priyesh/Vue/work/e3-unit-test/node_modules/axios/lib/core/dispatchRequest.js:59:10) at process._tickCallback (internal/process/next_tick.js:68:7) config: { transformRequest: { '0': [Function: transformRequest] }, transformResponse: { '0': [Function: transformResponse] }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: [Function: validateStatus], headers: { Accept: 'application/json, text/plain, */*', Accepts: 'application/json', 'Access-Control-Allow-Origin': '*' },   

i am setting up unit test with jest in my vuejs project.

testing with login component and i have tested successful all the props, input, client validation, but when i test with axios request POST then always return catch error

Error: Request failed with status code 404

login.spec.js

import Vue from 'vue'
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Login from '../../src/components/global/login/Login.vue';
import Raven from "raven-js";
import jQuery from 'jquery'
import Vuex from 'vuex'
import router from '../../src/router'
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

describe('Login.vue', () => {
let wrapper;
let componentInstance;
let mock;
beforeEach(() => {
    global.requestAnimationFrame = setImmediate,
    mock = new MockAdapter(axios)
    wrapper = shallowMount(Login, {
 router,
 $: jQuery,
 attachToDocument: true,
 mocks: {
   $t: () => { },
   Raven: Raven,
 },
data() {
      return {
         email: '',
        password: '',
      }
    }
  })
  componentInstance = wrapper.vm;
 })

  afterEach(() => {
   mock.reset()
})

my test code

 it('calls `axios()` with `endpoint`, `method` and `body`',async () => {
   const formData = {
     email: 'example@gmail.com',
     password: '111111'
   };

  let fackData = {"fack response"}
  mock.onPost(`${process.env.VUE_APP_BASE_URL}/login/`, 
  formData).reply(200, fackData);

   wrapper.vm.email = 'priyesh.vadhiya@gmail.com';
   wrapper.vm.password = 'aaaaaaa';
   wrapper.vm.doSigninNormal()
  });

Login.vue

 doSigninNormal() {
  const formData = {
  email: this.email,
  password: this.password
   };
   this.$v.$touch()
   if(this.$v.$invalid ){
        this.loading = false;
        this.emailLostFocus = true;
        this.passwordLostFocus = true;
        $('html, body').animate({scrollTop:110}, 'slow')
    }
   else{
     axios
        .post("/login", formData, {
           headers: { "X-localization": localStorage.getItem("lan") }
        })
        .then(res => {
         console.log('then',res);
         if (!res.data.result) {
               if (res.data.errors) {
                   for (var i = 0; i < res.data.errors.length; i++) {
                       this.$toaster.error(res.data.errors[i].message);
               if (
                     res.data.errors[0].message == "Your email is not yet verified"
                 ) {
                  this.showVerificationLinkButton = true;
                  }
                if (res.data.errors[i].field === "email") {
                    this.$toaster.error(res.data.errors[i].message);
                 }
           if (res.data.errors[i].field === "password") {
            this.$toaster.error(res.data.errors[i].message);
            }
           }
        }

        this.loading = false;
         this.$v.$reset();
         } else {
        this.loading = false;
       Raven.setUserContext({
          email: res.data.user.email,
           id: res.data.user.id
         });
       this.$store.dispatch("login", res);
      this.$v.$reset();
      }
    })
     .catch((err) => {
         console.log('catch',err);
     });

i am trying to lot. how to moke axios by calling method? positive answer appreciate

i want to call function and then call api(inside the function) and get response. wrapper.vm.doSigninNormal()

i have also post on stackOverflow to describe it.

kingjan1999 commented 5 years ago

Hi,

you are using axios-mock-adapter, not this project (jest-mock-axios). So you're wrong here, maybe someone can help you there.

However, you could replace axios-mock-adapter with jest-mock-axios . In this case, please refer to the README on how to use jest-mock-axios and report back if there is still an issue.