just tried to mocked the store then test the request with fetchMock but got this error :
you can check out the full repo on :
https://github.com/alibidjandy/layered-architecture
src/app/main/__tests__/main.test.tsx (5.569 s)
● Console
console.warn
Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.
7 | reducerPath: "productService",
8 | tagTypes: ["product"],
> 9 | baseQuery: fetchBaseQuery({
| ^
10 | baseUrl: serviceURL,
11 | }),
12 | endpoints: (builder) => ({}),
at fetchBaseQuery (node_modules/#reduxjs/toolkit/src/query/fetchBaseQuery.ts:180:13)
at Object.<anonymous> (src/app/main/data/api/service.ts:9:28)
at Object.<anonymous> (src/app/main/data/api/store.ts:3:1)
FAIL src/app/components/products/tests/products-requests.test.tsx
● Test suite failed to run
src/app/components/products/__tests__/products-requests.test.tsx:14:3 - error TS2304: Cannot find name 'fetchMock'.
14 fetchMock.resetMocks();
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:24:5 - error TS2304: Cannot find name 'fetchMock'.
24 fetchMock.mockResponse(JSON.stringify(dummyProducts));
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:41:5 - error TS2304: Cannot find name 'fetchMock'.
41 fetchMock.mockReject(new Error("Internal Server Error"));
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:61:5 - error TS2304: Cannot find name 'fetchMock'.
61 fetchMock.mockResponse(JSON.stringify(dummyProducts));
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:85:5 - error TS2304: Cannot find name 'fetchMock'.
85 fetchMock.mockReject(new Error("Internal Server Error"));
~~~~~~~~~
FAIL src/app/main/tests/service.test.ts (15.706 s)
● getProductById › request is correct
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
20 | .dispatch<any>(getProducts.initiate(undefined))
21 | .then(() => {
> 22 | expect(fetchMock).toBeCalledTimes(1);
| ^
23 | const { method, url } = fetchMock.mock.calls[0][0] as Request;
24 |
25 | expect(method).toBe("GET");
at src/app/main/__tests__/service.test.ts:22:27
● getProductById › unsuccessful response
TypeError: Cannot read property 'error' of undefined
51 | const {
52 | status,
> 53 | error: { error },
| ^
54 | isError,
55 | } = action;
56 | expect(status).toBe("rejected");
at src/app/main/__tests__/service.test.ts:53:20
● getProductById › request is correct
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
69 | .dispatch<any>(getProductById.initiate(dummyProduct.id))
70 | .then(() => {
> 71 | expect(fetchMock).toBeCalledTimes(1);
| ^
72 | const request = fetchMock.mock.calls[0][0] as Request;
73 | const { method, url } = request;
74 |
at src/app/main/__tests__/service.test.ts:71:27
● getProductById › unsuccessful response
TypeError: Cannot read property 'error' of undefined
102 | const {
103 | status,
> 104 | error: { error },
| ^
105 | isError,
106 | } = action;
107 | expect(status).toBe("rejected");
at src/app/main/__tests__/service.test.ts:104:20
Test Suites: 2 failed, 1 passed, 3 total
Tests: 4 failed, 3 passed, 7 total
Snapshots: 0 total
Time: 17.642 s
Ran all test suites.
install whatwg-fetch
after install it add import 'whatwg-fetch'; at the beginning (line 1) of the file.test youre using
The test in Jest doesn't run on the browser. It runs on NodeJS. So, you need a polyfill for the "fetch".
There are many options on NPM, but some of them haven't worked for me.
The one that worked fine was the cross-fetch: https://www.npmjs.com/package/cross-fetch
It works on browser/NodeJS/Mobile. You just need to add it to package.json (devDependencies) and import it on jest.setup.js file:
import 'cross-fetch/polyfill';
Related
When I try to run yarn start I have always this error :
node_modules/#types/react-router/index.d.ts(149,100):
Type expected. TS1110
147 | ): match<Params> | null;
148 |
> 149 | export type ExtractRouteOptionalParam<T extends string, U = string | number | boolean> = T extends `${infer Param}?`
I have used fetch to render my database in a table, I was trying to use bootstrap modal to render an specific document and edit it to post again in database. I think these two calls to the server overcharge it, and then it can't render the components, I just want to make sure if there is another way to do make the second call. When I run this display the result is:
Unhandled Rejection (TypeError): Failed to fetch
callApi
5 | Accept: "application/json",
6 | };
7 |
8 | const response = await fetch("http://localhost:3002/api" + url, options);
| ^ 9 | const data = await response.json();
10 | return data;
11 |
View compiled
list
.../src/api.js:29
26 | },
27 | sales: {
28 | list() {
29 | return callApi("/sales")
| ^ 30 | },
31 | create(sale) {
32 | return callApi("/sales", {
View compiled
fetchData
.../src/screens/sales/SalesScreen.js:29
26 |
27 | useEffect(() => {
28 | const fetchData = async () => {
29 | const response = await api.sales.list();
| ^ 30 | setSales(response);
31 | console.log(sales);
32 | const responseUsers = await api.users.list();
View compiled
(anonymous function)
.../src/screens/sales/SalesScreen.js:37
34 | console.log(users);
35 | };
36 |
37 | fetchData();
| ^ 38 | }, []);
39 |
40 | return (
View compiled
▶ 11 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error. Click the 'X' or hit ESC to dismiss this message.
If I run the first line of this code the app comes crashing down, I have been trying to do this simple thing and redirecting for hours.
const token = localStorage.getItem('usertoken') || '';
console.log('token', token);
if (token != undefined) {
console.log('a');
}
//error message
InvalidTokenError: Invalid token specified
./node_modules/jwt-decode/lib/index.js
D:/Code/bookreview/node_modules/jwt-decode/lib/index.js:9
__webpack_require__
D:/Code/bookreview/webpack/bootstrap:784
781 | };
782 |
783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 785 |
786 | // Flag the module as loaded
787 | module.l = true;
View compiled
fn
D:/Code/bookreview/webpack/bootstrap:150
147 | );
148 | hotCurrentParents = [];
149 | }
> 150 | return __webpack_require__(request);
| ^ 151 | };
152 | var ObjectFactory = function ObjectFactory(name) {
153 | return {
Edit: I was running this code in some other file without the if statement that was the problem. thanks
In the first line of your code, token is always being assigned a value, so token is never undefined. Since the default returned by getItem() is null you could change your code to be:
const token = localStorage.getItem('usertoken');
if (token) {
...
}
which will evaluate to true if token is not null, "", or some other falsy value.
./src/index.js
Line 26: Parsing error: Unexpected token in reactjs.
My code,
fetch('https://www.reddit.com/r/reactjs.json')
.then((result) => {
// Get the result
// If we want text, call result.text()
return result.json();
}).then((jsonResult) => {
// Do something with the result
console.log(jsonResult);
})
}
I tired to run a code error will be show,
Failed to compile
./src/index.js
Line 26: Parsing error: Unexpected token
24 | }
25 |
> 26 | fetch('https://www.reddit.com/r/reactjs.json')
| ^
27 | .then((result) => {
28 | // Get the result
29 | // If we want text, call result.text()
Im using the following npm librarie :
"react-accessible-accordion": "2.3.1",
it is returning an error to me :
ReferenceError: babelHelpers is not defined
(anonymous function)
C:/Users/tabm005/www/node_modules/react-accessible-accordion/dist/umd/index.js:1037
1034 |
1035 | var createReactContext = unwrapExports(lib);
1036 |
> 1037 | var _typeof = typeof Symbol === "function" && babelHelpers.typeof(Symbol.iterator) === "symbol" ? function (obj) {
1038 | return typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj);
1039 | } : function (obj) {
1040 | return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj);
View compiled
./node_modules/react-accessible-accordion/dist/umd/index.js.React__default
http://localhost:3000/static/js/bundle.js:121672:10
121669 | /***/ (function(module, exports, __webpack_require__) {
121670 |
121671 | (function (global, factory) {
> 121672 | true ? factory(exports, __webpack_require__(/*! react */ "./node_modules/react/index.js")) :
| ^ 121673 | typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
121674 | (factory((global.reactAccessibleAccordion = {}),global.React));
121675 | }(this, (function (exports,React) { 'use strict';
View source
./node_modules/react-accessible-accordion/dist/umd/index.js
C:/Users/tabm005/www/node_modules/react-accessible-accordion/dist/umd/index.js:5
2 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3 | typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4 | (factory((global.reactAccessibleAccordion = {}),global.React));
> 5 | }(this, (function (exports,React) { 'use strict';
6 |
7 | var React__default = 'default' in React ? React['default'] : React;
8 |
View compiled
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/Summary/summaryAccordion.js
http://localhost:3000/static/js/bundle.js:198742:85
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/stepsFormsContainer/stepsFormsContainer.js
http://localhost:3000/static/js/bundle.js:206311:84
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/stepsFormsContainer/index.js
C:/Users/tabm005/www/src/components/stepsFormsContainer/index.js:1
> 1 | import StepsFormsContainer from './stepsFormsContainer';
2 |
3 | export default StepsFormsContainer;
4 |
View compiled
▶ 5 stack frames were collapsed.
./src/components/stepperManager/index.js
C:/Users/tabm005/www/src/components/stepperManager/index.js:1
> 1 | import StepperManager from './stepperManager';
2 |
3 | export default StepperManager;
4 |
View compiled
▶ 12 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.
I tried several manipulations : remove my node_modules and package-lock.json and re-install the application. I tried a newer version of accordion too and no solution worked for me.
Any Idea ?
I added the babel librairies and that resolved my problem:
"babel": "^6.23.0",
"babel-core": "^6.26.3"