React test fails with react-hook-media-query - javascript

I'm using react-hook-media-query in my project but the test is failing because of it.
This is the code:
import React from 'react';
import useMediaQuery from 'react-hook-media-query';
const MyCompp = (props) => {
const minWidth1200 = useMediaQuery('(min-width: 1200px)');
...
}
test file:
import React from 'react';
import App from './App';
import { render } from '#testing-library/react';
import { WrapIntlProvider, WrapStore } from '../testsHelper';
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: () => ({
locale: 'en-US',
messages: {}
})
}));
describe('<App />', function () {
it('should render <App />', () => {
const { container } = render(
<WrapStore>
<WrapIntlProvider>
<App />
</WrapIntlProvider>
</WrapStore>
);
expect(container).toMatchSnapshot();
});
});
and when I run the tests it throws this error message:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config
option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/.../node_modules/react-hook-media-query/dist/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import
{ useState, useEffect } from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 2 | import useMediaQuery from 'react-hook-media-query';
| ^
Any ideas how to get rid of it?

Related

export import browser complaint cannot find module

This Meteor app has a template event that maks a Meteor.call, and is causing browser error Cannot find module 'server/plateCheck.js'. The file responsible is:
//app/imports/api/vehicles/methods.js
import { Meteor } from 'meteor/meteor'
import { Vehicles } from './vehicles.js'
import { plateCheck } from "../server/plateCheck.js"; //<<<<<<<<<<
Meteor.methods({
'extractPlateData': function (plate) {
console.log('method called: ', plate)
plateCheck(plate)
}
)},
//app/imports/api/vehicles/server/plateCheck.js
import {Vehicles} from '../imports/api/vehicles/vehicles.js'
const plateCheck = async (plateNumber) => {...}
module.exports = plateCheck;
meteor list includes ecmascript 0.15.1
Why is this and isn't the export/import correct as stated? How to get read of the error? Thanks.
Your relative path is wrong. The server folder is in the same directory as methods.js, so you'll need to import
import { plateCheck } from "./server/plateCheck.js";
Or you can make all imports absolute:
//app/imports/api/vehicles/methods.js
import { plateCheck } from "/imports/api/server/plateCheck.js";
...
//app/imports/api/vehicles/server/plateCheck.js
import {Vehicles} from '/imports/api/vehicles/vehicles.js'

Error when run the test "Cannot find module "

I am new to writing Unit tests and i am trying to write unit tests to my react application using testing-library/react and jest
Here is the test code "Home.test.js"
import React from 'react';
import {render, cleanup} from '#testing-library/react';
import '#testing-library/jest-dom/extend-expect';
import Home from "../src/Home";
afterEach(cleanup);
describe("Tests for HomePage", function() {
it("should render without throwing an error", function() {
const { homePage } = render(<Home />);
//check something here
});
});
Here is my code in component "Home.js"
import * as React from "react";
import { Panel, Shell, Button } from "#myorg/core";
import { home_icon, new_icon } from "#myorg/icons";
function Home(props) {
const openDialog = React.useCallback(() => {
//do something
});
return (
<Shell.Page breadcrumbs={[t("demo:Home")]}>
<Panel style={{ height: "100%" }}>
<h2>App Header</h2>
<Button onClick={openDialog} variant="primary">
<img src={new_icon} width="20" />
{t("demo:New Asset")}
</Button>
</Panel>
</Shell.Page>
);
}
error I get when I run "npm run test"
Cannot find module '#myorg/icons' from 'Home.js'
I believe you are trying to use the tsconfig.json options paths, which will be ignored by jest (or by other testing frameworks). You need to manually replicate all your paths definition in jest.config.js and manually keep them updated using the jest config option moduleNameMapper like this:
moduleNameMapper: {
// translate all your custom paths here, read the doc in the link above
'^#finder/(.*)$': '<rootDir>/files-manipulation/$1',
'^#metadata/(.*)$': '<rootDir>/folder-metadata/$1',
'^#logger/(.*)$': '<rootDir>/logging/$1',
// ...and so on
},

Alternative for "component: () => import()" in VueJS routing

I downloaded a template online to better understand VueJS and also create a web app. However I have a problem with routing. There is a function in my router's index.js that imports a path. The import syntax seems to be buggy due to some webpack issues. I tried a lot of different things but couldn't fix the bug so I want to find a workaround for that import syntax
This is my code for router's index.js
import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'
// Routes
import paths from './paths'
// import views from './views'
function route (path, view, name) {
return {
name: name || view,
path,
component: () => import(
`../views/${view}.vue`
)
}
}
Vue.use(Router)
// Create a new router
const router = new Router({
mode: 'history',
routes: paths.map(path => route(path.path, path.view, path.name)).concat([
{ path: '*', redirect: '/home' }
]),
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
if (to.hash) {
return { selector: to.hash }
}
return { x: 0, y: 0 }
}
})
Vue.use(Meta)
// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if (process.env.GOOGLE_ANALYTICS) {
Vue.use(VueAnalytics, {
id: process.env.GOOGLE_ANALYTICS,
router,
autoTracking: {
page: process.env.NODE_ENV !== 'development'
}
})
}
export default router
When i try to build it, I get an error saying:
ERROR in ./src/router/index.js
Module build failed: SyntaxError: C:/djangoProjects/martin - Copy/martin/src/router/index.js: Unexpected token (15:21)
The syntax error is on line (15:21), in the route function on the component: () => import( line and exactly on import. Fixing this issue is a pain so I was wondering if there is a workaround for it without using the import syntax?
If I remember correctly you'll need a plugin for babel that can handle dynamic imports.
Check out:
https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import
Run npm install #babel/plugin-syntax-dynamic-import
Create or open .babelrc
{
"plugins": ["#babel/plugin-syntax-dynamic-import"]
}

Failing Jest unit testing

I have a component in which I wrote test for. It worked great but now something is going wrong and I cannot figure out what.
This is the simple component which takes two numbers and returns their sum:
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { LogOutButton } from './LogOutButton.js';
class Home extends React.Component {
displayName = Home.name;
state = {
result: 0,
val1: 0,
val2: 0,
};
handleChangeOne = event => {
this.setState({ val1: event.target.value });
};
handleChangeTwo = event => {
this.setState({ val2: event.target.value });
};
add = () => {
this.setState({
result: parseInt(this.state.val1) + parseInt(this.state.val2)
});
};
onLogoutClick = () => {
window.location.href = 'https://www.MICROSOFT.com';
}
render() {
return (
<div>
<h1>Hello world! The result is: {this.state.result}</h1>
<input type="text" onChange={this.handleChangeOne} />
+
<input type="text" onChange={this.handleChangeTwo} />
= <br />
<button onClick={this.add}>Add</button>
<br/><br/>
<LogOutButton onLogout={this.onLogoutClick} />
</div>
);
}
}
export default Home;
And this is the test which used to work great:
import React from 'react';
import { shallow } from 'enzyme'
import ReactDOM from 'react-dom';
import App from './App';
import { Home } from './components/Home';
describe('Home />', () => {
it('Renders a sum', () => {
const home = shallow(<Home />);
var first_value = home.state().val1;
var second_value = home.state().val2;
var result = first_value + second_value;
expect(result).toBe(0);
const inputs = home.find('input');
inputs.at(0).simulate('change', {target: {value: 5} } );
inputs.at(1).simulate('change', { target: { value: 8 } });
home.find('button').simulate('click');
home.update();
expect(home.state().result).toBe(13);
});
});
This is the error that I get:
FAIL src/Home.test.js
● Test suite failed to run
C:/Users/Itay/Documents/Experiments/WebApplication1/WebApplication1/ClientApp/src/components/Home.js: Unexpected token (8:12)
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
6 |
7 | class Home extends React.Component {
> 8 | displayName = Home.name;
| ^
9 |
10 | state = {
11 | result: 0,
What's going on here? I have tried several things but nothing helped so far.
To make your test run I had to add this in package.json:
"enzyme-adapter-react-16": "1.6.0"
And this in the test:
import Enzyme, { shallow } from 'enzyme';
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
The test then passed.
Note that I tested this in a CRA 2.1 environment. https://github.com/facebook/create-react-app
is your app compiling OK? do you have separate babel configs for app and tests?
i think Jest complains about the line utilizing field declarations syntax, which is stage-3 proposal right now.
Anyway, displayName is class property IIRC, so I think you should call it with static keyword, like this:
static displayName = Home.name;
Although I am not sure what this line is supposed to do, can you elaborate on that? you don't need to set displayName explicitly if you don't need it to be different than name inferred from class name

React Native jest test: TypeError: Cannot read property 'unsubscribeFromTopic' of undefined

I'm using react-native-fcm and jest to test my React Native app. I have a pretty basic test, it looks like this:
import 'react-native';
import React from 'react';
import PushController from '../app/PushController';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('works correctly', () => {
const tree = renderer.create(
<PushController />
);
});
And PushController is somewhat large, so here's the interesting parts
import React, { Component } from 'react';
import { AsyncStorage } from 'react-native';
import FCM from 'react-native-fcm';
export default class PushController extends Component {
(...)
componentDidMount() {
if (this.notificationListener) this.notificationListener.remove();
this.notificationListener = FCM.on('notification', (notif) => {
if (!notif.local_notification) {
this.notifyUser(notif.coffee);
}
});
FCM.unsubscribeFromTopic('/topics/coffee');
FCM.subscribeToTopic('/topics/coffee');
}
(...)
However, when running the test I get
__tests__/PushControllerTest.js
● works correctly
TypeError: Cannot read property 'unsubscribeFromTopic' of undefined
at Object.FCM.unsubscribeFromTopic (node_modules/react-native-fcm/index.js:86:15)
at PushController.componentDidMount (app/PushController.js:44:26)
at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:265:25
at measureLifeCyclePerf (node_modules/react-test-renderer/lib/ReactCompositeComponent.js:75:12)
at node_modules/react-test-renderer/lib/ReactCompositeComponent.js:264:11
at CallbackQueue.notifyAll (node_modules/react-test-renderer/lib/CallbackQueue.js:76:22)
at ReactTestReconcileTransaction.ON_DOM_READY_QUEUEING.close (node_modules/react-test-renderer/lib/ReactTestReconcileTransaction.js:36:26)
at ReactTestReconcileTransaction.TransactionImpl.closeAll (node_modules/react-test-renderer/lib/Transaction.js:206:25)
at ReactTestReconcileTransaction.TransactionImpl.perform (node_modules/react-test-renderer/lib/Transaction.js:153:16)
at batchedMountComponentIntoNode (node_modules/react-test-renderer/lib/ReactTestMount.js:69:27)
I've tried including lots of stuff in the test, like jest.mock('react-native-fcm') and others, but I can't get it to work at all. I get that jest automatically mocks the library, but I don't understand why FCM is undefined. Any ideas?
I managed to solve it, finally! Simply needed to change my test to
import 'react-native';
import React from 'react';
import PushController from '../app/PushController';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
import FCM from 'react-native-fcm'; // <-- This
it('works correctly', () => {
FCM.unsubscribeFromTopic = jest.fn(); // <-- These two
FCM.subscribeToTopic = jest.fn();
const tree = renderer.create(
<PushController />
);
});
To make sure the actual calls are mocked. I did a lot of googling before this, so I'm sure this will be useful for someone.

Categories

Resources