How to mock a css import for jest/enzyme test? - javascript

I need to mock an imported CSS file in my jest/enzyme test:
Header.test.js
import React from 'react'
import { shallow } from 'enzyme'
import { Header } from './Header'
jest.mock('semantic-ui-css/semantic.min.css') // <-- no effect...
it('should render page title', () => {
const wrapper = shallow(<Header title='Test' />)
expect(wrapper.find('title').text()).toEqual('Test')
})
I do get the error for the import 'semantic-ui-css/semantic.min.css' line:
Test suite failed to run
/Users/node_modules/semantic-ui-css/semantic.min.css:11
#import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic&subset=latin);/*!
^
SyntaxError: Invalid or unexpected token
I don't need import the css file for the test. So I would like to mock that import out for the test. How can I do that?
I tried to do jest.mock('semantic-ui-css/semantic.min.css') but that doesn't work.
This is how the Header.js looks like:
Header.js
import Head from 'next/head'
import 'semantic-ui-css/semantic.min.css'
export const Header = props => {
return (
<Head>
<meta http-equiv='content-type' content='text/html;charset=UTF-8' />
<meta charset='utf-8' />
<title>{props.title}</title>
<link rel='icon' href='/static/favicon.ico' />
<link rel='stylesheet' href='/_next/static/style.css' />
</Head>
)
}

Use ignore-styles package in your jest config.
npm install --save-dev ignore-styles
In your jest.config.js file include these lines
import register from 'ignore-styles';
register(['.css', '.sass', '.scss']);
jest-css-modules is the another package you can try.

Related

An icon of fontawesome doesn't apeear in react code

I try to assimilate an icon of fontawesome in react and the icon not apeear and I get an error in the console.
Here's the code:
import PropTypes from "prop-types";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
const SearchBar = ({ handleChange }) => {
return (
<div className="field">
<FontAwesomeIcon icon="fa-regular fa-magnifying-glass" />
<input
type="search"
className="text-rtl form-control"
placeholder="חפש מוצר"
onInput={handleChange}
/>
</div>
);
};
SearchBar.propTypes = {
handleChange: PropTypes.func.isRequired,
};
export default SearchBar;
And in the file of the index.html I worte the js code:
<script
src="https://kit.fontawesome.com/ab8447aa04.js"
crossorigin="anonymous"
></script>
And I connected to the site of fontawesome. So Why there is a problem?
You no need for react-fontawesome package, you have a Fontawesome CDN in index.html
<script
src="https://kit.fontawesome.com/ab8447aa04.js"
crossorigin="anonymous"
></script>
just add <i className="fa-regular fa-magnifying-glass"></i>
I think your configuration is mixed up between react & non react usage. For react, you don't need to include the script in index.html.
For react there are three dependencies -
npm i --save #fortawesome/fontawesome-svg-core
npm install --save #fortawesome/free-solid-svg-icons
npm install --save #fortawesome/react-fontawesome
After that it is as simple as -
// import icon component
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
// import the icon
import { faCoffee } from "#fortawesome/free-solid-svg-icons";
// usage
<FontAwesomeIcon icon={faCoffee} />

Import leaflet in single component svelte

I'm using in a single component leaflets plugin, for the moment I put the js and css in public/index.html but i need to find a way to import only the js and css in the single component. Also i tryed with svelte::head but it didn't work. Also this project is going to be used like a node_modules, so i need to find a way to not put the js and css files in folder public. Any suggestions? I tryed to import leaflet installing leaflet with npm and import like
import from 'leaflet'
import * as L from 'leaflet'
but it didn't work.
You can import the styles using rollup-plugin-css-only. To avoid the ugly css import with a relative path to node_modules you may want to use postcss instead: https://medium.com/#bekzatsmov/how-to-import-css-from-node-modules-in-svelte-app-2a38b50924ff
This is based on the standard Svelte template: https://github.com/sveltejs/template
App.svelte
<script>
import * as L from 'leaflet';
import '../node_modules/leaflet/dist/leaflet.css'; // It might be better to use postcss.
import { onMount } from 'svelte';
let div = null;
onMount(() => {
let map = L.map(div, {
center: [17.385044, 78.486671],
zoom: 10
});
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
});
</script>
<div bind:this={div} style="height: 100vh; width: 100%;"></div>
main.js
import App from './App.svelte';
const app = new App({
target: document.body
});
rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: false,
emitCss: true
}),
css({ output: 'public/build/bundle.css' }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
export default app;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Svelte app</title>
<link rel='icon' type='image/png' href='/favicon.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>
</head>
<body>
</body>
</html>

React importing material-ui components not working

I'm new to React. I have a local development server (node http-server) and have installed material-ui package.
According to the material-ui docs, to add a component, I simply import it like any other module:
import Button from '#material-ui/core/Button';
However, when I try this, my webserver is returning a 404 and Firefox console outputs this: Loading module from “http://localhost:8080/node_modules/#material-ui/core/Button/” was blocked because of a disallowed MIME type (“text/html”)
The directory is accessible because I can reference the ./node_modules/#material-ui/core/Button/Button.js file and it is returned by http-server. But if I import that file, I get
SyntaxError: import not found: default.
I've tried importing index.js from that directory, but get same error.
How do I import the Button component (as shown in the material-ui example) correctly?
Here is my code (being served by http-server on localhost:8080)
(I am using npx babel to compile the JSX to js before serving)
test.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test React</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="app"></div>
<!-- React scripts -->
<script type="module" src="./test.js"></script>
</body>
</html>
test.js:
import { Mod1 } from './module1.js';
export class TestComponent extends React.Component
{
render()
{
return <h1>Hello world!</h1>;
}
}
export const TestC2 = () =>
{
return <h2>This is a h2</h2>;
}
ReactDOM.render(<div><TestComponent /><TestC2 /><Mod1 /></div>, document.getElementById('app'));
module1.js
// module1
import Button from './node_modules/#material-ui/core/Button';
export class Mod1 extends React.Component
{
constructor(props)
{
super(props);
this.state = {};
}
componentWillMount(props)
{
console.log("willMount", props);
}
componentDidMount(pp, ps)
{
console.log("didMount", pp, ps);
}
render()
{
console.log('render', this.props, this.state);
return <Button />;
}
}

Example of setting webpack public path at runtime

I am struggling to find an example of how to set the public path of an output file of a webpack bundle.
The documentation says:
If you don't know the publicPath while compiling, you can omit it and
set __webpack_public_path__ on your entry point.
Like so:
__webpack_public_path__ = myRuntimePublicPath
Would anyone be kind enough to create a JSFiddle example how this can be done?
Nothing has changed after almost two years. It's still surprisingly difficult to find an example of setting public path for webpack at runtime.
Prerequisites
webpack 4.5.0
an app big enough to leverage code splitting
For simplicity let's say our html lives in index.html and app entry point is app.js
An example that works
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script type="application/javascript">
window.resourceBasePath = '/path/to/scripts/on/server/';
</script>
<script type="application/javascript" src="/path/to/scripts/on/server/app.js"></script>
</body>
</html>
app.js
// it is important to set global var before any imports
__webpack_public_path__ = window.resourceBasePath;
import React from 'react';
import ReactDOM from 'react-dom';
import {store, history} from './store';
const render = () => {
import('./root').then((module) => {
const Root = module.default;
ReactDOM.render(
<Root
store={store}
history={history}
/>,
document.getElementById('app'),
);
});
};
render();
if (module.hot) {
module.hot.accept('./root', render);
}
An example that doesn't work
Webpack publicPath documentation says it's enough just to set a global variable with the right name. I did that:
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script type="application/javascript">
__webpack_public_path__ = '/path/to/scripts/on/server/';
</script>
<script type="application/javascript" src="/path/to/scripts/on/server/app.js"></script>
</body>
</html>
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import {store, history} from './store';
const render = () => {
import('./root').then((module) => {
const Root = module.default;
ReactDOM.render(
<Root
store={store}
history={history}
/>,
document.getElementById('app'),
);
});
};
render();
if (module.hot) {
module.hot.accept('./root', render);
}
In this case my app fails complaining in console it couldn't load 0.js from current path to index.html. Which means that setting public path didn't have any impact.

How to use the API defined in 3rd party library in webpack+reactjs

I am using webpack + react as my application. Below is my index.jsx file.
import $ from 'jquery'
import React from 'react';
import ReactDOM from 'react-dom';
import load from 'little-loader';
import './main.css';
import './component';
import Search from './search/search'
load('http://api.map.baidu.com/api?v=2.0&ak=gNO2wKVBNupZfafi0bl0sW3dIKqAHn4l', function(err){
console.log('err:', err);
});
// load('baidu.js');
// document.body.appendChild(component());
ReactDOM.render(<Search />, document.getElementById('search'));
var map = new BMap.Map("container");
It imports a third party javascript from this link: http://api.map.baidu.com/api?v=2.0&ak=gNO2wKVBNupZfafi0bl0sW3dIKqAHn4l.
If you open this link, the content is defined as follows:
(function(){
window.BMap_loadScriptTime =
(new Date).getTime();
document.write('<script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak=gNO2wKVBNupZfafi0bl0sW3dIKqAHn4l&services=&t=20160401164342"></script>');
})();
Now I want to use the api from this library by
var map = new BMap.Map("container");
But I got an error complaining BMap is not defined. I guess I didn't import this library correctly, how should I import it?
My index.html looks like below:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id='search'>
</div>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>

Categories

Resources