Testing React Components: How does it work? - javascript

In the jest docs, I found this simple example of testing react components:
// Link.react.test.js
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';
test('Link changes the class when hovered', () => {
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseEnter();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseLeave();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
Why do we have to import React and react-test-renderer, but not have to import other test specific things, like test, expect?
Can someone explain, how this works under the hood and what actually happens when the tests are run?

It finds the binary jest and executes it with your script, this binary would compile your code first then run it, so those modules for testing would be imported during compiling time when those function keyword was found. You install Jest to your original application to test component. React module or others it really your stuff.
Update
By tracing the repository of Jest
jest/packages/jest-runtime/src/script_transformer.js, We could found out it utilize Node.js module VM to run the script, and it has some method like vm.createContext() and vm.Script().runInContext(), so those internal module should be imported to sandbox programmatically.
Example from VM
const vm = require('vm');
const sandbox = { globalVar: 1 }; // <=> import expect, test
vm.createContext(sandbox);
...
vm.runInContext('globalVar *= 2;', sandbox); // <=> Our test code.
So those module such as expect, and test may be imported like what vm.createContext() does above.
It's hard to exactly know how this be done in a short time, but we still could get some clues:
in jest/packages/jest-runtime/src/cli/index.js
...
import Runtime from '../'; // ---> jest/packages/jest-runtime/src/index.js
export function run(...) {
...
Runtime.createContext(
...
).then(
const runtime = new Runtime(config, environment, hasteMap.resolver);
runtime.requireModule(filePath);
...
)
}
Runtime is a critical class defined in
jest/packages/jest-runtime/src/index.js
...
import Resolver from 'jest-resolve';
...
import ScriptTransformer from './script_transformer';
...
requireModule() {
_execModule(...)
}
...
_execModule() {
...
this._createRequireImplementation(
...
this._createJestObjectFor(...)
}
Many critical works here, require module, detect the environment config, has Resolver to find the module id, to detect what kind of the module, should it be mocked, return jestObject, wrap all to our sandbox for testing.
Here is its core to do mock

Related

Vue - Import npm package that has no exports

I am trying to import an npm package into a Vue component.
The package (JSPrintManager - here) is just a JavaScript file with no exports. Consequently, I cannot use:
import { JSPM } from "jsprintmanager"
I have also had no success with the following:
import JSPM from "jsprintmanager"
import * as JSPM from "../../node_modules/jsprintmanager/JSPrintManager"
import * as JSPM from "../../node_modules/jsprintmanager/JSPrintManager.js"
Am I barking up the wrong tree?
If there is no way to import an npm package that is not a module, is there another way to load the relevant JavaScript file (currently residing in my node-modules directory) into my component?
I am using the Vue CLI
jspm.plugin.js
import * from '../../node_modules/jsprintmanager/JSPrintManager';
export default {
install(Vue) {
Vue.prototype.$JSPM = window.JSPM
}
}
main.js
import Vue from 'vue'
import JSPM from './jspm.plugin';
Vue.use(JSPM);
In any of your components you can now access JSPM as this.$JSPM
If you want to use it outside of your components (say, in store) and you want it to be the same instance as the one Vue uses, export it from Vue, in main.js
const Instance = new Vue({
...whatever you have here..
}).$mount('#app');
export const { $JSPM } = Instance
Now you can import { $JSPM } from '#/main' anywhere.
That would be the Vue way. Now, in all fairness, the fact your import is run for the side effect of attaching something to the window object which you then inject into Vue is not very Vue-ish. So the quick and dirty way to do it would be, in your component:
import * from '../../node_modules/jsprintmanager/JSPrintManager';
export default {
data: () => ({
JSPM: null
}),
mounted() {
this.JSPM = window.JSPM;
// this.JSPM is available in any of your methods
// after mount, obviously
}
}
The main point of the above "simpler" method is that you have to make the assignment after the page finished loading and running the JSPM code (and window.JSPM has been populated).
Obviously, if you disover it sometimes fails (due to size, poor connection or poor hosting), you might want to check window.JSPM for truthiness and, if not there yet, call the assignment function again after in a few seconds until it succeeds or until it reaches the max number of tries you set for it.

Webpack dynamic import .json file?

I'm using React Intl for x number of languages (example below) and at the moment Im importing the following where I setup my App:
import { addLocaleData } from 'react-intl';
import locale_en from 'react-intl/locale-data/en';
import locale_de from 'react-intl/locale-data/de';
import messages_en from './translations/en.json';
import messages_de from './translations/de.json';
addLocaleData([...locale_en, ...locale_de]);
...
export const messages = {
en: messages_en,
de: messages_de
}
Since these language files are being imported no matter which language is being used my main bundle js file is getting pretty big, especially from the .json files.
How can I with Webpack split these language files (or copy them to my dist folder using CopyWebpackPlugin) and then dynamically import them based on the language being used at the moment?
The app is isomorphic so this same code is being run on the server.
I've been working on something like this lately, although I don't need SSR for my project. I found that pairing dynamic import syntax with React's Suspense component achieves the desired result. Here's a rough overview of what I found to work, at least in my case, which doesn't include SSR:
// wrap this around your JSX in App.js:
<React.Suspense fallback={<SomeLoadingComponent />}>
<AsyncIntlProvider>
{/* app child components go here */}
</AsyncIntlProvider>
</React.Suspense>
// the rest is in support of this
// can be placed in another file
// simply import AsyncIntlProvider in App.js
const messagesCache = {};
const AsyncIntlProvider = ({ children }) => {
// replace with your app's locale getting logic
// if based on a hook like useState, should kick off re-render and load new message bundle when locale changes (but I haven't tested this yet)
const locale = getLocale();
const messages = getMessages(locale);
return (
<IntlProvider locale={locale} messages={messages}>
{children}
</IntlProvider>
);
};
function getMessages(locale) {
if (messagesCache[locale]) {
return messagesCache[locale];
}
// Suspense is based on ErrorBoundary
// throwing a promise will cause <SomeLoadingComponent /> to render until the promise resolves
throw loadMessages(locale);
}
async function loadMessages(locale) {
// dynamic import syntax tells webpack to split this module into its own chunk
const messages = await import('./path/to/${locale}.json`);
messagesCache[locale] = messages;
return messages;
}
Webpack should split each locale JSON file into its own chunk. If it doesn't, something is likely transpiling the dynamic import syntax to a different module system (require, etc) before it reaches webpack. For example: if using Typescript, tsconfig needs "module": "esnext" to preserve import() syntax. If using Babel, it may try to do module transpilation too.
The chunk output for a single locale will look something like this; definitely more than would be achieved via CopyWebpackPlugin:
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{
/***/ "./path/to/en-US.json":
/*!*************************************!*\
!*** ./path/to/en-US.json ***!
\*************************************/
/*! exports provided: message.id, default */
/***/ (function(module) {
eval("module.exports = JSON.parse(\"{\\\"message.id\\\":\\\"Localized message text\\\"}\");//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9zcmMvbG9jYWxpemF0aW9uL2VuLVVTLmpzb24uanMiLCJzb3VyY2VzIjpbXSwibWFwcGluZ3MiOiIiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./path/to/en-US.json\n");
/***/ })
}]);
Hopefully, this is a good starting point and either works with SSR or can be modified to work with SSR. Please report back with your findings on that subject. 🙂

Jest mocking default exports - require vs import

I have seen questions referring to the mocking of default exports with jest around here, but I don't think this has already been asked:
When mocking the default export of a dependency of a module that is being tested, the tests suite fails to run if the module imports the dependency with the ES6 import statement, stating TypeError: (0 , _dependency.default) is not a function It succeeds, however, if the module uses a require().default call instead.
In my understanding, import module from location directly translates to const module = require(location).default, so I am very confused why this is happening. I'd rather keep my code style consistent and not use the require call in the original module.
Is there a way to do it?
Test file with mock:
import './modules.js';
import dependency from './dependency';
jest.mock('./dependency', () => {
return {
default: jest.fn()
};
});
// This is what I would eventually like to call
it('calls the mocked function', () => {
expect(dependency).toHaveBeenCalled();
});
Dependency.js
export default () => console.log('do something');
module.js (not working)
import dependency from './dependency.js';
dependency();
module.js (working)
const dependency = require('./dependency.js').default;
dependency();
You can use either es6 import or require js to import your js files in your jest tests.
When using es6 import you should know that jest is trying to resolve all the dependencies and also calls the constructor for the class that you are importing. During this step, you cannot mock it. The dependency has to be successfully resolved, and then you can proceed with mocks.
I should also add that as can be seen here jest by default hoists any jest.mocks to the top of the file so the order in which you place your imports does not really matter.
Your problem though is different. Your mock function assumes that you have included your js file using require js.
jest.mock('./dependecy', () => {
return {
default: jest.fn()
};
});
When you import a file using require js, this is the structure it has:
So assuming I have imported my class called "Test" using require js, and it has method called "doSomething" I could call it in my test by doing something like:
const test = require('../Test');
test.default.doSomething();
When importing it using es6 import, you should do it differently though. Using the same example:
import Test from '../Test';
Test.doSomething();
EDIT: If you want to use es6 import change your mock function to:
jest.mock('./dependecy', () => jest.fn());
the short answer for ES module if you want to use
import dependency from 'dependency'
jest.mock('dependency', () => ({
...jest.requireActual('dependency'),
__esModule: true,
default: jest.fn(),
}))
Have you tried something like this? I was dealing with the default export mocking for months until I found this.
jest.mock('./dependency', () => () => jest.fn());
The idea behind this line is that you are exporting a module that is a function. So you need to let Jest knows that it has to mock all your ./dependency file as a function, that returns a jest.fn()

Import components for server-side rendering in ES6

I've got a nice little ES6 React component file (simplified for this explanation). It uses a library that is browser-specific, store This all works beautifully on the browser:
/app/components/HelloWorld.js:
import React, { Component } from 'react';
import store from 'store';
export default class HelloWorld extends Component {
componentDidMount() {
store.set('my-local-data', 'foo-bar-baz');
}
render() {
return (
<div className="hello-world">Hello World</div>
);
}
}
Now I'm trying to get it to render on the server as follows, using babel-register:
/server/routes/hello-world.js:
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import HelloWorld from '../../app/components/HelloWorld'
export default function(req, res) {
res.render('root', {
reactHTML: ReactDOMServer.renderToString(<HelloWorld />),
});
}
I get an error from the node server saying "window is not defined" due to importing 'store'. Ideally I could conditionally import by detecting the environment (node vs browser), but conditional imports aren't supported in ES6.
What's best way to get around this? I don't actually need to execute the browser code (in this case componentDidMount won't be called by ReactDOMServer.renderToString) just get it running from node.
One way would be using babel-rewire-plugin. You can add it to babel-register via the plugins option
require('babel/register')({
plugins: ['babel-rewire-plugin']
});
Then rewire your store dependency to a mocked store:
HelloWorld.__Rewire__('store', {
set: () => {} // no-op
});
You can now render HelloWorld from the server peacefully.
If you want to suppress the load of some npm module, you can just mock it.
Put this on your node.js application setup, before the HelloWorld.js import:
require.cache[require.resolve('store')] = {
exports: {
set() {} // no-op
}
};
This value will be used instead of the real module, which doesn't need on your purposes. Node.js module API is stable, so this behavior will not be broken and you can rely on it.

How to test React component without Browserify

I have a react application that doesn't uses the browserify tool.
It means that the React variable is exported by the script of the react js lib called in the <head>.
// React variable is already available
var MyComponent = React.createClass({});
After implementing this component, I want to create a test for it.
I took a look at Jest documentation and I've created my component test.
/** #jsx React.DOM */
jest.dontMock('../compiled_jsx/components/my-component.js');
describe('MyComponent', function() {
it('The variables are being passed to component', function() {
var React = require('react/addons');
// In the `MyComponent` import I got the error below:
// ReferenceError: /compiled_jsx/components/my-component.js: React is not defined
var myComponent = require('../compiled_jsx/components/my-component.js');
});
In the Jest documentation example, both component and its tests uses the require function for getting the React variable.
Is there any way to expose React variable into the component?
Or it's necessary using browserify for creating this test?
Jest runs in node.js, so you need to use commonjs modules. You don't use browserify with jest. If you're really against commonjs modules you can do this assuming each file is wrapped in an iffe.
var React = typeof require === 'undefined'
? window.React
: require('react/addons');
Or alternatively as the first line of your tests, try:
global.React = require('react/addons');
And either way, export your components using:
try { module.exports = Foo; } catch (e) { window.Foo = Foo };
Personally, I don't think jest is practical if you're not using commonjs modules.

Categories

Resources