vue-test-utils, jest; ReferenceError: Request is not defined

Viewed 294

I'm making a POST API call using ES6 Request() constructor in my vue.js application. The implementation works fine but my test suite (I'm using Jest with vue-test-utils) fails with the below error:

ReferenceError: Request is not defined

Here's the code snippet of my test case:

 it('Expect login to pass validation on submit', ()=> {
    const $router = {
      push : jest.fn()
    }
    // const validateLogin = jest.fn();
    const executeLoginSpy = jest.spyOn(wrapper.vm, 'executeLogin');
    wrapper = mount(Login, {
      localVue,
      vuetify,
      mocks: { $router },
      stubs: ['router-link'],
      data() {
        return {
          login: {
              email: 'test@testmail.com',
              password: 'test@@@@@@@@123'
          }
        }
      }
    });
    const button = wrapper.find('.submit-btn');
    button.trigger('click');
    expect(executeLoginSpy).toHaveBeenCalled();
    expect($router.push).toBeCalledWith('/');
});

I'm also attaching a snippet of my implementation using Request().

  const request = new Request('/api/token', {
    method: 'POST',
    body: formData,
  });

Any help would be appreciated. Thanks in advance!

1 Answers

the problem is that the fetch and other APIs are not available on your node. They are available in the browser

Install https://www.npmjs.com/package/jest-fetch-mock as a dev dependency and set it up correctly. Request and fetch will work as expected.

Related