Comments (14)
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.
Jesus. I misspelled __mocks__
(missing s)!
from jest-mock-axios.
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.
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.
OK, I was too fast. Of couse the promise
variable is the issue here. lib/mock-axios.ts#L54
from jest-mock-axios.
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.
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.
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.
@knee-cola any chance you have some ideas on why this would be happening?
from jest-mock-axios.
I ran into the same problem today.
from jest-mock-axios.
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.
@knee-cola yes it is transforming TypeScript
from jest-mock-axios.
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.
@timthompson nice catch, that was pretty non-obvious :)
from jest-mock-axios.
Related Issues (20)
- axios.CancelToken.source() returns `undefined` HOT 7
- jest-mock-axios incompatible with CRA 4 / resetMocks: true HOT 8
- mockAxios doesn't implement `isAxiosError` HOT 1
- How to use with ES5 require() syntax HOT 2
- unexpected token error HOT 2
- Unable to mock requests when testing API end point HOT 2
- Is there a better way to separate multiple requests with the same url and method–eg. params? HOT 2
- Testing code using an Axios instance HOT 2
- Doesn't work in native ESM HOT 2
- Using with vue component tests HOT 6
- version 4.6.0 gives SyntaxError: Cannot use import statement outside a module HOT 7
- How to use with common js project? HOT 1
- TypeError: Cannot read properties of undefined (reading 'then') in component axios call HOT 13
- Typescript error TS:1005, TS:1131, TS:1109, and TS:1128 HOT 1
- UnhandledPromiseRejection when returing `Promise.reject` on interceptor HOT 6
- Error when using with @slack/web-api HOT 1
- MockAxios.defaults is different on github from published npm package HOT 1
- TypeError: _jestMockAxios.default.reset is not a function HOT 1
- Support request handling for multiple requests? HOT 3
- types are no longer exported HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jest-mock-axios.