GithubHelp home page GithubHelp logo

Comments (14)

timthompson avatar timthompson commented on June 25, 2024 28

I ran across this same issue and thought I would comment for anyone else that may come across this issue.

If the problem isn't the spelling/placement of the __mocks__ directory, another potential cause of this issue that isn't really spelled out in the docs but makes sense after looking at the source is the mockAxios.mockResponse() or mockAxios.mockError() call should come after your axios call is triggered in your test code.

If it comes before the axios call is triggered then you will get this error.

So trigger the call, then tell mockAxios how you want it to respond.

from jest-mock-axios.

dotnetCarpenter avatar dotnetCarpenter commented on June 25, 2024 5

Jesus. I misspelled __mocks__(missing s)!

from jest-mock-axios.

danawoodman avatar danawoodman commented on June 25, 2024 2

I ended up just using direct mocking using Jest that works pretty well:

import axios from 'axios'
import http from './http'

jest.mock('axios')

test('should return data', async () => {
  const url = '/foo'
  const resp = { data: 'bar' }
  axios.get.mockReturnValue(resp)
  const data = await http.get(url)
  expect(axios.get).toBeCalledWith(url)
  expect(data).toBe(resp.data)
})

from jest-mock-axios.

dotnetCarpenter avatar dotnetCarpenter commented on June 25, 2024

I looked through my local jest-mock-axios package but since it's transpiled I didn't get much out of it. Looking at the source on github, it becomes much more clear. The error in the stack trace points to lib/mock-axios.ts#L66.

What is not clear is from where the response is suppose to come from. Since we are mocking an HTTP call, I expect that non existing end-points can be used for testing.

from jest-mock-axios.

dotnetCarpenter avatar dotnetCarpenter commented on June 25, 2024

OK, I was too fast. Of couse the promise variable is the issue here. lib/mock-axios.ts#L54

from jest-mock-axios.

dotnetCarpenter avatar dotnetCarpenter commented on June 25, 2024

Hmm.. The README says that mockAxios.mockResponse can be called with { data: 'server says hello!' } but that doesn't looks like the signature for public mockResponse(response?:HttpResponse, promise:SyncPromise=null):void {.

What am I missing?

from jest-mock-axios.

dotnetCarpenter avatar dotnetCarpenter commented on June 25, 2024

I've never written typescript so I might be wrong but let's assume that the type HttpResponse does nothing, then { data: 'world' } will be mixed in the response object.

Node: v8.9.4
jest: 22.0.6

from jest-mock-axios.

danawoodman avatar danawoodman commented on June 25, 2024

I'm having this same issue but have the __mocks__ folder spelled correctly. Perhaps there is another reason for this?

Even though I'm passing in a promise this error throws, which is unexpected.

I am using TypeScript and this is a sample of the code I'm working with:

// currency.ts
import axios from 'axios'

const CURRENCY_API = '/v1/currency'

class Currency {
  static price() {
    return axios
      .get(CURRENCY_API)
      .then((resp: axios.Response) => Number(resp.data[0].price_usd))
      .catch((error: Error) => console.log(error))
  }
}

export default Currency
// currency.test.ts
import mockAxios from 'jest-mock-axios'
import Currency from './currency'

describe('server/models/currency', () => {
  afterEach(() => mockAxios.reset())

  describe('.price', () => {
    test('returns the correct currency valule', async () => {
      const resp = { data: [{ price_usd: '15000' }] }
      mockAxios.mockResponse(resp)
      const actual = await Currency.price()
      expect(mockAxios.get).toHaveBeenCalled()
      const expected = 15000
      expect(actual).toBe(expected)
    })
  })
})

from jest-mock-axios.

danawoodman avatar danawoodman commented on June 25, 2024

@knee-cola any chance you have some ideas on why this would be happening?

from jest-mock-axios.

DominicGebhart avatar DominicGebhart commented on June 25, 2024

I ran into the same problem today.

from jest-mock-axios.

knee-cola avatar knee-cola commented on June 25, 2024

I have managed to reproduce the original error reported by @dotnetCarpenter and can confirm he's findings . This problem can be caused by mispelling the "mocks" directory. The mocking file needs to ne placed inside the mocks directory - not the *mock dir.

@danawoodman have you configured Jest to transform TypeScript before running the tests?

Here's a sampe jest.config.js file (it's used in one of my projects, which contains Axios tests):

module.exports = {
    "verbose": true,
    "testRegex": "/test/.*\\.spec\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js"
    ],
    "transform": {
        "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    }
};

Also here's the tsconfig.js:

{
    // docs: https://basarat.gitbooks.io/typescript/content/docs/project/tsconfig.html
    "compilerOptions": {
        "noImplicitAny": true,
        // module resolution strategy ('node','classic')
        "moduleResolution": "node",
        //  ECMAScript target version ('ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT')
        "target": "ESNEXT",
        // module code generation ('commonjs', 'amd', 'system', 'umd' or 'es2015')
        "module": "commonjs",
        // create declaration files in output folder
        "declaration": true,
        "declarationDir": "./"
    },
    // excluding folders from being included
    // while creating `declaration` files
    "exclude": [
        "test",
        "__mocks__"
    ]
}

from jest-mock-axios.

danawoodman avatar danawoodman commented on June 25, 2024

@knee-cola yes it is transforming TypeScript

from jest-mock-axios.

vnugent avatar vnugent commented on June 25, 2024

I'm seeing the same error as described by OP. The dir is correctly spelled as mocks.

node: v7.10.0

  "dependencies": {
    "axios": "~0.17.1",
    "axios-mock-adapter": "~1.12.0",
    "react": "~16.2.0",
    "react-dom": "~16.2.0",
    "react-router-dom": "^4.2.2",
    "react-scripts-ts": "2.13.0"

from jest-mock-axios.

somanysteves avatar somanysteves commented on June 25, 2024

@timthompson nice catch, that was pretty non-obvious :)

from jest-mock-axios.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.