question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

'mockImplementation' and 'mockResolvedValue' are not functions when mock 'axios'

See original GitHub issue

Do you want to request a feature or report a bug? Probably a bug

What is the current behavior? When I try to mock axios as in docs and run my test it’s failed:

import React from 'react';
import axios from 'axios';
import withFetching from './api';
import Educations from '../components/Educations/index';
import { URL_PATH_EDUCATIONS } from '../constants/index'
import { shallow, render, mount } from 'enzyme';


describe('WithFetching', () => {
  const WithFetching = withFetching(URL_PATH_EDUCATIONS, Educations); // withFetching is HOC

  jest.mock('axios');

  it('should fetch educations', () => {
    const resp = { data: [{ name: 'FooBar' }]};
    axios.get.mockImplementation(() => Promise.resolve(resp));

    return wrapper._fetchData().then(educations => expect(educations).toEqual(resp.data));
  });
});

And it shows me the error: TypeError: _axios2.default.get.mockImplementation is not a function The same happens with axios.get.**mockResolvedValue**(resp);

What is the expected behavior? No error is presented and mockResolvedValue(resp), mockImplementation are functions and work as described in docs

Please provide your exact Jest configuration From my package.json

...
"jest": {
    "verbose": true,
    "transform": {
      "^.+\\.js$": "babel-jest"
    },
    "globals": {
      "NODE_ENV": "test"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|scss)$": "identity-obj-proxy"
    },
    "setupFiles": [
      "./test/jestsetup.js"
    ],
    "snapshotSerializers": [
      "./node_modules/enzyme-to-json/serializer"
    ]
  },
"devDependencies": {
    ...
    "axios": "^0.18.0",
    "babel-jest": "^22.4.3",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-to-json": "^3.3.3",
    "jest": "^22.4.3",
    "react": "^16.3.1",
    "react-addons-test-utils": "^15.6.2",
    "react-dom": "^16.3.1",
    "react-test-renderer": "^16.3.1",
    ...
  },

jestsetup.js:

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

// Before using Jest in React@16 and React@15 Adapter has to be installed
configure({ adapter: new Adapter() });

console.error = message => {
   throw new Error(message);
};

Enviroment:

  System:
    OS: macOS High Sierra 10.13.3
    CPU: x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz
  Binaries:
    Node: 9.8.0
    Yarn: 1.5.1
    npm: 5.8.0
  npmPackages:
    jest:
      wanted: ^22.4.3
      installed: 22.4.3

I already saw the Issue#5962 and I am not sure but they are maybe connected somehow

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:8
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

125reactions
SimenBcommented, Apr 15, 2018

jest.mock is hoisted to the top of its scope, not the top of Program. Just move jest.mock to the same scope as your import.

@@ -5,12 +5,11 @@ import Educations from '../components/Educations/index';
 import { URL_PATH_EDUCATIONS } from '../constants/index'
 import { shallow, render, mount } from 'enzyme';
 
+jest.mock('axios');
 
 describe('WithFetching', () => {
   const WithFetching = withFetching(URL_PATH_EDUCATIONS, Educations); // withFetching is HOC
 
-  jest.mock('axios');
-
   it('should fetch educations', () => {
     const resp = { data: [{ name: 'FooBar' }]};
     axios.get.mockImplementation(() => Promise.resolve(resp));

Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

33reactions
rkentmccommented, Aug 13, 2018

I am having the same issue and my jest.mock(‘axios’); is in scope with import.

import ReactDOM from 'react-dom';
import App from '../App';
import renderer from 'react-test-renderer';
import axios from 'axios';
import Dropdown from '../Dropdown';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

jest.mock('axios');

configure({ adapter: new Adapter() });

test ('mock API call', () => {
    const resp =  { data: [{name: 'Data'}]};
    axios.get.mockResolvedValue(resp);
    console.log(Dropdown.componentDidMount());

    return Dropdown.componentDidMount().then(app => expect(app).toContain(resp.data))
});
├── public
└── src
    ├── __tests__
    │   └── __snapshots__
    └── main
        └── resources
            └── META-INF

I am using the CRA package.json with the react-scripts.

I am getting the error: TypeError: _axios2.default.get.mockResolvedValue is not a function

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeError: axios.get.mockResolvedValue is not a function ...
Can someone help me understand why moving jest.mock('axios') inside the testblock (or inside any function, for that matter) results in an error?
Read more >
The only 3 steps you need to mock an API call in Jest
Yeah, how to type mock functions is not immediately clear. Try this: (axios.get as jest.Mock).mockResolvedValue(fakeResp).
Read more >
Mock Functions
function to automatically mock the axios module. Once we mock the module we can provide a mockResolvedValue for .get that returns the data...
Read more >
mockresolvedvalueonce is not a function
jest mockresolvedvalue not working ... could not get value to mock function ... const axios = require('axios'); // At the same scope with...
Read more >
axios.AxiosPromise.mockResolvedValue JavaScript and ...
How to use. mockResolvedValue. function. in. AxiosPromise · Best JavaScript code snippets using axios.AxiosPromise.mockResolvedValue(Showing top 3 results out of ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found