Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
egor-sorokin opened this issue Apr 15, 2018 · 7 comments

Comments

@egor-sorokin
Copy link
Contributor

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

@SimenB
Copy link
Member

SimenB commented 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.

@SimenB SimenB closed this as completed Apr 15, 2018
@egor-sorokin
Copy link
Contributor Author

egor-sorokin commented Apr 15, 2018

Thanks! I just haven't found that we have to keep jest.mock and import in the same scope.

@SimenB
Copy link
Member

SimenB commented Apr 15, 2018

PR welcome to update/clarify docs 🙂

@rkentmc
Copy link

rkentmc commented 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

@SimenB
Copy link
Member

SimenB commented Aug 14, 2018

See #6832

@rochabianca
Copy link

same problem here on Vue

MichaelDeBoey added a commit to MichaelDeBoey/gatsby-remark-embedder that referenced this issue Dec 24, 2019
* Added support for streamable embeds

* Reverting mistaken README changes

* Removing last line inserted by prettier ...

* Fixing up Twitter section ...

* Updating to use HTML embed code from Streamable API

* fixing linting

* Fixing last of validation errors

* Update README.md

Co-Authored-By: Michaël De Boey <info@michaeldeboey.be>

* Updating PR in response to code review feedback

* Fixing single quote issue and updating readme

* Renaming test, alphabetized kitchen sink test

* Extracted mockFetch, though there is a dependency on jest usage that requires the mocking of node-fetch to occur in each test file (jestjs/jest#5993), updated tests

* undo mock fetch extraction and inline expected html result

* Apply suggestions from code review

Co-Authored-By: Michaël De Boey <info@michaeldeboey.be>

* Using URL dependency, removed extra bit from Readme

* Adding test coverage for more verbose logic

* Simplified shouldTransform function

* Update tests

* Update docs

* Updating shouldTransform

* Further updates to shouldTransform method

* Updating to simply use array.includes

* Added suggested changes

* Added getNormalizedStreamableUrl function

* Fixing normalized streamable URL

* fix linting rule

* fix

* Extract normalized var

* Cleanup code

* Cleanup tests

* Add Streamable to package.json keywords

* Update iframe test

Co-authored-by: Michaël De Boey <info@michaeldeboey.be>
anuraghazra pushed a commit to anuraghazra/gatsby-remark-embedder that referenced this issue Feb 5, 2020
* Added support for streamable embeds

* Reverting mistaken README changes

* Removing last line inserted by prettier ...

* Fixing up Twitter section ...

* Updating to use HTML embed code from Streamable API

* fixing linting

* Fixing last of validation errors

* Update README.md

Co-Authored-By: Michaël De Boey <info@michaeldeboey.be>

* Updating PR in response to code review feedback

* Fixing single quote issue and updating readme

* Renaming test, alphabetized kitchen sink test

* Extracted mockFetch, though there is a dependency on jest usage that requires the mocking of node-fetch to occur in each test file (jestjs/jest#5993), updated tests

* undo mock fetch extraction and inline expected html result

* Apply suggestions from code review

Co-Authored-By: Michaël De Boey <info@michaeldeboey.be>

* Using URL dependency, removed extra bit from Readme

* Adding test coverage for more verbose logic

* Simplified shouldTransform function

* Update tests

* Update docs

* Updating shouldTransform

* Further updates to shouldTransform method

* Updating to simply use array.includes

* Added suggested changes

* Added getNormalizedStreamableUrl function

* Fixing normalized streamable URL

* fix linting rule

* fix

* Extract normalized var

* Cleanup code

* Cleanup tests

* Add Streamable to package.json keywords

* Update iframe test

Co-authored-by: Michaël De Boey <info@michaeldeboey.be>
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants