Search code examples
vuejs2jestjsvue-test-utils

ReferenceError: Response is not defined


Short Version:

I am writing a test case for my Vue component using vue-test-utils and jest.

I am trying to create a Response object in one of my test cases, but I keep getting error ReferenceError: Response is not defined

Long Version

I am trying to mock an API response when a Vuex action is dispatched using jest. I have created a Vuex action like this

let fakeAccountList = [
  {"id":"abcd","title":"Random Account 1"},
  {"id":"pqrs","title":"Random Account 2"}
]
actions = {
   getAccounts: jest.fn(()=>{

     return new Promise((resolve, reject)=>{
       resolve(mockResponse(200,'ok',fakeAccountList))
      })
    })
 }

The getAccounts action returns a Promise which resolves to a list of accounts. The mockResponse function is as shown:

mockResponse = (status, statusText, response) => {

  return new Response(response, {
    status: status,
    statusText: statusText,
    headers: {
      'Content-type': 'application/json'
    }
  });
};

When mockResponse is called, I get the error ReferenceError: Response is not defined

I found this very old issue: https://github.com/facebook/jest/issues/930 The comments suggest that it was fixed,but, it is not working for me. I do not want to import extra libraries such as isomorphic-fetch just for this.

Here is my devDependencies in package.json:

"devDependencies": {
    "@vue/cli-plugin-babel": "3.0.3",
    "@vue/cli-plugin-e2e-cypress": "3.0.3",
    "@vue/cli-plugin-eslint": "3.0.3",
    "@vue/cli-plugin-unit-jest": "3.0.3",
    "@vue/cli-service": "3.0.3",
    "@vue/test-utils": "1.0.0-beta.25",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "23.6.0",
    "less": "3.0.4",
    "less-loader": "4.1.0",
    "lodash": "4.17.10",
    "node-sass": "4.9.2",
    "sass-loader": "7.0.3",
    "vue-template-compiler": "2.5.16",
  }

Any help would be appreciated. Thanks in advance


Solution

  • I am using a react application and just adding the below statement in your mock file resolved the issue. Hope this might be helpful for you or others.

    import 'isomorphic-fetch'