Axios捕获错误请求失败,状态码为404

时间:2019-03-25 13:48:06

标签: unit-testing vue.js jestjs axios axios-mock-adapter

我正在测试使用Axios的登录组件。我尝试使用axios-mock-adapter来模拟Axios,但是运行测试时,仍然出现以下错误:

Error: Request failed with status code 404

如何在测试中正确模拟Axios?

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()
  })

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

    let fakeData = { data: "fake response" }
    mock.onPost(`${process.env.VUE_APP_BASE_URL}/login/`, formData).reply(200, fakeData);

    wrapper.vm.email = 'example@gmail.com';
    wrapper.vm.password = '111111';
    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 => {
      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);
    });
  }
}

4 个答案:

答案 0 :(得分:3)

测试错误的登录URL

根本问题是测试代码将axios-mock-adapter设置在与Login.vue中实际使用的URL不同的URL上,因此该请求未存根:

// login.spec.js:
mock.onPost(`${process.env.VUE_APP_BASE_URL}/login/`, formData).reply(200, fakeData)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

// Login.vue
axios.post("/login", formData)
            ^^^^^^

解决方法是使测试代码使用相同的URL(即/login):

// login.spec.js
mock.onPost("/login", formData).reply(200, fakeData)

需要等待axios.post()

单元测试不等待POST请求,因此该测试将无法可靠地验证调用或响应(没有黑客)。

解决方法是更新doSigninNormal()以返回axios.post()承诺,以允许呼叫者等待结果:

// Login.vue
doSigninNormal() {
  return axios.post(...)
}

// login.spec.js
await wrapper.vm.doSigninNormal()
expect(mock.history.post.length).toBe(1)

验证登录结果

要验证结果,您可以声明一个本地数据道具以保存登录结果1️⃣,更新doSigninNormal()以处理响应(在测试中用fakeData模拟),捕获结果2️⃣然后,只需等待doSignInNormal()后检查该数据属性即可。

// Login.vue
data() {
  return {
    ...
    result: '' 1️⃣
  }
}
methods: {
  doSignInNormal() {
    return axios.post(...)
            .then(resp => this.result = resp.data.result) 2️⃣
  }
}

// login.spec.js
const result = await wrapper.vm.doSigninNormal()
expect(result).toBe(fakeData.result)
expect(wrapper.vm.result).toBe(fakeData.result)

Edit Mocking Axios calls with axios-mock-adapter

答案 1 :(得分:1)

  

如果axios实例适配器(xhr或http)由axios-mock-adapter接管,则会出现错误的baseURL配置,如下所示:

{baseURL:'/for/bar'} 

如果我们发送如下请求:

get('/api/v1/exampleService')

最后一个http请求将变为

'http://host:port/for/bar/for/bar/api/v1/exampleService'

由于模拟适配器接管了axios默认适配器,因此将传递与模拟规则不匹配的api,并由默认适配器进行处理,这两个适配器选择逻辑都将通过此处(core / dispatchRequest.js):

if (config.baseURL && !isAbsoluteURL(config.url)) { 
   config.url = combineURLs(config.baseURL, config.url);
}

因此,如果您使用模拟,请使用以http://

开头的完整网址

答案 2 :(得分:0)

模拟Axios:

有两种简单的方法可以模拟axios,因此您的测试不会执行真正的http请求,而是使用模拟对象:

将axios设置为组件属性:

import axios from 'axios`;
Vue.component({
  data() {
    return {
      axios,
    }
  },
  methods: {
    makeApiCall() {
      return this.axios.post(...)
    }
  }
})

因此,您可以轻松地在测试中注入模拟:


it('test axions', function() {
  const post = jest.fn();
  const mock = {
    post,
  }
  // given 
  const wrapper = shallowMount(myComponent, {
    data: {
      axios: mock,
    }
  });

  // when
  wrapper.vm.makeApiCall();

  // then
  expect(post).toHaveBeenCalled();
});

我认为这是最直接的方法。

使用插件在每个组件中注入axios

您可以设置vue-plugin-axios之类的插件来自动将axios注入每个组件,例如:

  makeApiCall(){
    this.$axios.post(...)
  }

无需在data中明确声明它。

然后在您的测试中,而不是将模拟作为data的一部分传递,而是将其作为mocks的一部分传递,这是vue-test-utils处理全局注入的方式:

it('test axions', function() {
  const post = jest.fn();
  const mock = {
    post,
  }
  // given 
  const wrapper = shallowMount(myComponent, {
    mocks: {
      $axios: mock,
    }
  });

  // when
  wrapper.vm.makeApiCall();

  // then
  expect(post).toHaveBeenCalled();
});

这是模拟axios调用以防止调用真实axios并执行真实http请求的方法。

配置模拟行为和访问调用参数

使用jest.fn,您可以设置一个模拟函数以返回特定对象,例如:

const post = jest.fn( () => ({status: 200, response: ...}) )

您还可以通过hasBeenCalledWith' method, or more complex stuff via mock.calls`(more info here)访问该呼叫的参数:

expect(post).toHaveBeenCalledWith(expectedParams)

因此,您的最终测试应类似于我认为的以下内容:

it('calls axios() with endpoint, method and body',async (done) => {

  // given
  const formData = { email: 'example@gmail.com', password: '111111' };
  const fakeResponse = {response: "fake response"};
  const email = 'example@gmail.com';
  const uri = 'somepath/login/'; // I dont think you can access Vue process env variables in the tests, so you'll need to hardcode.
  const password = '11111';

  const post = jest.fn(() => Promise.resolve({status: 200}) );

  const mock = {
    post,
  }
  const wrapper = shallowMount(Component, {
    data() {
      return {
        axios: mock,
        // email,
        // password, // you could do this instead to write to wrapper.vm later
      }
    }
  });
  wrapper.vm.email = 'example@gmail.com';
  wrapper.vm.password = '111111';

  // when
  await wrapper.vm.doSigninNormal();

  // then
  expect(post).toHaveBeenCalledWith({uri, password, email});

  // or
  const calls = post.mock.calls;
  const firstParam = calls[0][0];

  expect(firstParam.uri).toBe(uri);
  expect(firstParam.email).toBe(email);
  expect(firstParam.password).toBe(password);

  done();

});

答案 3 :(得分:0)

问题在axios-mock-adapter包装上。它需要使用.create()方法的axios实例。 看这里: creating an instance

在您的App.js中, 使用:

import axios from "axios";
const instance = axios.create();

instance.post("http://localhost/api/user/update", {name: "Test"}, {headers: {"Authorization": "Bearer token")}});

尽管测试中没有任何改变。

我从axios-mock-adapter的测试中得到了提示。

这样的例子是: post test