Comments (28)
Getting TypeError: this.realFetch is not a function
as well whenever I try to make a POST request in non-testing code
fetch(myApiRoute, {method: 'POST'})
Edit:
Just realized this will work, it needs to have a fetch passed into its context, not the global context.
fetchMock.useNonGlobalFetch(fetch)
fetchMock.mock(myApiRoute, 'POST', payload)
from fetch-mock.
I had exactly this problem, using fetch-mock 4.1.1 and isomorphic-fetch 2.2.1. To resolve it I had to do all of the following:
- don't
import isomorphic-fetch
in the action code (under test). If I did, I always got theonly absolute urls
error. - to polyfill for older browsers,
import whatwg-fetch;
in the action instead. - in the test class,
import isomorphic-fetch;
alongsideimport fetch-mock;
(edited following further simplification)
Hope this helps.
from fetch-mock.
@wheresrhys it seems like some people have resolved this issue but I'm doing everything the same and still getting the error from node-fetch:
Error: only absolute urls are supported
The only thing I've noticed about the example from @dr-nick that's different than mine (and I understand it is just a snippet and not full working code) is that it's not testing the response from the async action (using a then statement). Once I try to return the response from the async request, I still get the error, and I don't see a way that error wouldn't be thrown judging by the stack trace and the construct of the Request object.
Sorry to reopen this but I just wanted to know if this was considered resolved or if there was still being more done to solve it.
Here's a snippet of my test that's failing:
describe("async", function() {
beforeEach(function() {
fetchMock.useNonGlobalFetch(fetch);
fetchMock.mock(API_URL, { body: { response: ['value'] }});
})
afterEach(function() {
fetchMock.restore();
})
it("runs fetch and collects response", function() {
const store = mockStore({entities: {}});
return store.dispatch(actions.action())
.then(() => {
expect(true).to.equal(true);
})
})
})
from fetch-mock.
I see. So I need to use whatwg-fetch's Request implementation probably. Will have a look in the new year
from fetch-mock.
Or here https://github.com/wheresrhys/fetch-mock/blob/master/src/fetch-mock.js#L65 I can most likely just return a Request-like object as I'm only interested in comparing a few properties, not the internals
from fetch-mock.
fixed in 3.1.1. Cheers for raising the issue
from fetch-mock.
Thanks for this!
from fetch-mock.
Sorry to open this old issue, but I came across the same error (Error: only absolute urls are supported : Request failed
) and I was wondering if you could take a look. I constructed the test exactly as outlined above by jwarby, which is more or less:
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import fetch from 'isomorphic-fetch';
/* ... */
global.fetch = fetch;
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('actions', () => {
afterEach(() => {
fetchMock.restore();
});
fetchMock
.mock('<url>');
});
This is the stack trace:
at Object.assert [as default] (node_modules/expect/lib/assert.js:20:9)
at Expectation.toEqual (node_modules/expect/lib/Expectation.js:69:26)
at dispatch (node_modules/redux-mock-store/lib/index.js:55:48)
at node_modules/redux-thunk/lib/index.js:9:74
at dispatch (node_modules/redux/lib/applyMiddleware.js:46:18)
I get the same error with nock
. I am using fetch-mock 4.1.0 and isomorphic-fetch 2.2.0. The bizarre thing is that I have been advised to use fetch-nock to get around this problem. Am I missing anything obvious?
from fetch-mock.
try importing isomorphic fetch before fetch mock. And you don't need to assign it to a local variable - isomorphic fetch will already set itself as a global
from fetch-mock.
No luck unfortunately :( Thanks for your reply, will probably try to mock the whole thing.
from fetch-mock.
If your code is public on github I don't mind having a look to see what the problem is. There's probably something in the way you're requiring your js that I haven't considered, and which is causing node-fetch to be included instead of whatwg-fetch and I'd like to either fix it or add to the troubleshooting guide.
from fetch-mock.
I'm sure I am. It's not public, but this is basically it:
require('isomorphic-fetch');
import fetchMock from 'fetch-mock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from '../actions/users';
import {
LOAD_USERS
} from '../actions/users';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('user actions', () => {
var user;
beforeEach(function() {
contract = {
name: "Ericat",
email: "[email protected]"
};
});
afterEach(() => {
fetchMock.restore();
});
it('creates LOAD_USERS', (done) => {
fetchMock
.mock('http://127.0.0.1:8080/v1/users', {users: [user]});
const expectedActions = [
{ type: LOAD_USERS },
{ type: LOAD_USERS, body: { users: [user] } }
];
const store = mockStore({ users: [] },
expectedActions,
done);
store.dispatch(actions.loadUsers())
});
});
from fetch-mock.
@dr-nick sorry but I am very confused:
- by "action code under test", do you mean in the test itself? Because in the last bullet point you seem to be saying the opposite;
- Do you suggest using
whatwg-fetch
instead ofisomorphic-fetch
and callingglobal.fetch()
in my actual code?
Thank you very much for your time
from fetch-mock.
@ericat my bad, I'd been through so many permutations trying to make it work that I lost the power of writing!
- I mean the code being tested - i.e. the redux action creator.
- I did, although by tweaking the import syntax I've since dropped the need to mess around with explicitly namespacing
global
, so now only the first part holds true. I've revised the comment to simplify (and lose the confusing last bullet!).
Here's some barebones working code:
fetch.js
import 'whatwg-fetch'; // don't specify `as` or `from` as this polyfills into global namespace anyway
...
export function saveQuery(query) {
return dispatch => {
dispatch(storeQuery(query));
fetch(`SAVE_URL${query}`))
.then(
resp => dispatch(receiveResults(resp)),
error => dispatch(logError(error))
);
};
}
FetchTest.js
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import 'isomorphic-fetch'; // don't specify `as` or `from` as this polyfills into global namespace anyway
import * as actions from 'actions/fetch';
...
describe('fetch async creators', () => {
const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
afterEach(() => {
fetchMock.restore();
});
it('should dispatch expected actions for saving a query', (done) => {
fetchMock.mock(/SAVE_URL.+/, {
savedTerm: true,
});
const priorState = {};
const expectedActions = [
{
type: STORE_QUERY,
query: 'some query',
}
];
const store = mockStore(priorState, expectedActions, done);
store.dispatch(actions.saveQuery('some query'));
});
});
tl;dr: replace isomorphic-fetch
with whatwg-fetch
in the action creator module alone, make sure you don't assign it to a variable, and you should be golden.
from fetch-mock.
@ericat, did you ever manage to resolve this issue? I am running into it now with my test suite... @dr-nick's suggestion didn't solve the problem but it did bring about a different error - after reorganising my imports in tests and swapping to whatwg-fetch in my action creators I then got TypeError: this.realFetch is not a function
. Does anyone have any further suggestions?
from fetch-mock.
I plan to make the behaviour a bit better anyway. A colleague of mine raised this issue a few days ago too
from fetch-mock.
The useNonGlobalFetch
did the trick for me too, although if in the documentation it is marked as deprecated.
from fetch-mock.
@sstrong-pica9 - did you ever figure this out? I'm still getting the error as well.
from fetch-mock.
Reopening as it's obviously still an ongoing problem. But to investigate I need somebody to post a minimal test case i.e. a repo I can clone, install and attempt to run a test on. It's not an issue I've ever been able to recreate. I have recently (v4.5.4) fixed a bug whereby mocking fetch was not properly scoped to a test/test-group, which may have some bearing on this issue
from fetch-mock.
Thanks @wheresrhys . I'll see if I can extract to a repo this weekend... I am using 4.5.4, and will test with an older version as well. Let you know how it goes.
from fetch-mock.
I think there's too many outside dependencies on my side to confirm this is a fetch-mock issue. (I switched to another fetch mocking utility and got the same result).
Going to dig further, there's definitely an issue, just not sure where its coming from.
Fine to close in the meantime, will comment if I can pinpoint it. Thanks!
from fetch-mock.
I am having the same issues...
"[Error: only absolute urls are supported]"
@dr-nick 's solution worked at first, but then I pulled in https://github.com/redux-effects/redux-effects-fetch and my tests broke with this error again...
from fetch-mock.
@sallakarppinen sorry for the late reply! I am using nock at the moment, everything appears to be working fine. I have put the test in a gist, in case it's useful to someone https://gist.github.com/Ericat/84151d8abdde2e1f228f39bea58b3f04
from fetch-mock.
I ran into this in v5.0 as well. As far as I can tell, the issue seems to be related to use of a non-global fetch
. fetch-mock does not seem to apply to those - is it supposed to? I was able to work around the problem by using global.fetch
everywhere. This stack trace helped me find the problem, gathered by using e.stack in my promise's .catch()
:
Error: only absolute urls are supported
at ./node_modules/node-fetch/index.js:54:10
at new Fetch (./node_modules/node-fetch/index.js:49:9)
at Fetch (./node_modules/node-fetch/index.js:37:10)
at module.exports (./node_modules/isomorphic-fetch/fetch-npm-node.js:8:19)
at callAPI (my-code-under-test.js:37:10)
Note that fetch-mock
is nowhere to be found in the trace - my code under test is going straight into the 'real' fetch implementation.
Using mocha
2.4.5, isomorphic-fetch
2.2.1, and fetch-mock
5.0.1.
from fetch-mock.
There are lots of notes on use with non-global fetch here http://www.wheresrhys.co.uk/fetch-mock/installation. If they don't address your problem please provide a minimal test case of your problem (ideally as a repo I can clone, install and attempt to run a test in)
from fetch-mock.
Oh, I don't actually have a problem anymore, using global everywhere solved it. Was just hoping to help others that ran into the same problem. It's just weird to be using globals again after so long, but that's the fetch standard for you =)
I don't really think it's a bug if fetch
is supposed to be global. If however your intent is to make this work even if someone uses an import, then I can probably help. I just need to finish my real work first and I can make a repo.
from fetch-mock.
same error, does anyone figure it out ?
I am using NOCK as the API mock tool, and using thunk as async middleware action
from fetch-mock.
I can confirm that for me at least, in my entry point to my app,
import 'isomorphic-fetch'
, and only in the tests where code is involved that calls fetch,
import 'isomorphic-fetch'
import fetchMock from 'fetch-mock'
totally works.
from fetch-mock.
Related Issues (20)
- Problem with fetch-mock and HMR HOT 3
- Update node-fetch dependency to v3.x.x HOT 5
- Querystring is deprecated
- Unable to use fetch-mock as ES6 import HOT 10
- fetch-mock: No fallback response defined for GET to https://jsonmock.hackerrank.com/api/stocks/?date=1-January-2002
- [Bug] Using fetch-mock with the decorator function results in internal error HOT 5
- When a matcher fails because a header matches the key but not the value, other matchers aren't considered
- Returning different values for different requests on the same URL HOT 3
- Response always undefined in .calls? HOT 1
- regenerator global Function call throws CSP unsafe-eval error HOT 2
- Typescript: FetchMockSandbox and native fetch have incompatible types HOT 1
- [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" HOT 1
- Response.error() is not being treated as a response HOT 1
- Allow access to `express`-style path parameters in mocked endpoints
- done() not recognised matched requests
- fetch-mock not working after update to Node v18 HOT 4
- "SyntaxError: Cannot use import statement outside a module" when importing fetchMock from fetch-mock HOT 2
- es5/client-legacy-bundle.js uses es6 syntax resulting in errors for older browsers HOT 1
- does it support import.meta.hot?
- fallbackToNetwork does not work with relative URLs 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 fetch-mock.