I have a project being built with webpack. This allows me to import .svg files to create React components.
When running tests I have been attempting to avoid using webpack to avoid tying the mocha version to a webpack plugin. Unfortunately, when the .svg imports are hit, they fail to be found. We are also using css modules, and they allowed me to use the css-modules-require-hook to work around the importing of css files.
Is there a technique I could use to accomplish the same thing with SVGs?
I saw this solved by using require.extensions (in node this is deprecated, but should never go away) to force importing these types of assets to result in an no-op. Starting mocha with the --require flag lets us configure the runtime environment for our tests so starting mocha like this:
NODE_PATH=./app mocha -w --compilers js:babel-core/register --require ./app/lib/testHelper.js --require ./app/lib/testNullCompiler.js 'app/**/*.spec.#(js|jsx)' --watch-extensions js,jsx
where testNullCompiler.js is:
const noop = () => 1;
require.extensions['.css'] = noop;
require.extensions['.scss'] = noop;
require.extensions['.png'] = noop;
require.extensions['.jpg'] = noop;
require.extensions['.jpeg'] = noop;
require.extensions['.gif'] = noop;
require.extensions['.svg'] = noop;
This will cause all the above types of files to return the noop function instead of attempting to load the actual file.
My code is using the es6 import syntax but I'm assuming that babel is converting that to require under the covers which enables this technique to work.
Yes, I just find a way to mock .svg module for mocha here.
Mocha can use require hooks to deal with universal javascript import, such as babel-register for .js.
You can use require-hacker to add hooks to extensions of modules.
You can use a null react component mock for other component loaders such as react-svg-loader to load .svg as a react component.
here is the example:
import requireHacker from 'require-hacker';
const fakeComponentString = `
require('react').createClass({
render() {
return null;
}
})
`;
// for fake component
requireHacker.hook('svg', path => `module.exports = ${fakeComponentString}`);
Related
Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.
it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {
const { queryByTestId, queryByText } = render(
<Tooltip id="test" message="test" />,
)
fireEvent.mouseOver(queryByTestId('tooltip'))
expect(queryByText('test')).toBeInTheDocument()
fireEvent.mouseOut(queryByTestId('tooltip'))
expect(queryByText('test')).not.toBeInTheDocument()
cleanup()
})
I keep getting the error TypeError: expect(...).toBeInTheDocument is not a function
Has anyone got any ideas why this is happening? My other tests to render and snapshot the component all work as expected. As do the queryByText and queryByTestId.
toBeInTheDocument is not part of RTL. You need to install jest-dom to enable it.
And then import it in your test files by:
import '#testing-library/jest-dom'
As mentioned by Giorgio, you need to install jest-dom. Here is what worked for me:
(I was using typescript)
npm i --save-dev #testing-library/jest-dom
Then add an import to your setupTests.ts
import '#testing-library/jest-dom/extend-expect';
Then in your jest.config.js you can load it via:
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
]
When you do npm i #testing-library/react make sure there is a setupTests.js file with the following statement in it
import '#testing-library/jest-dom/extend-expect';
Having tried all of the advice in this post and it still not working for me, I'd like to offer an alternative solution:
Install jest-dom:
npm i --save-dev #testing-library/jest-dom
Then create a setupTests.js file in the src directory (this bit is important! I had it in the root dir and this did not work...). In here, put:
import '#testing-library/jest-dom'
(or require(...) if that's your preference).
This worked for me :)
Some of the accepted answers were basically right but some may be slightly outdated:
Some references that are good for now:
https://github.com/testing-library/jest-dom
https://jestjs.io/docs/configuration
Here are the full things you need:
in the project's <rootDir> (aka where package.json and jest.config.js are), make sure you have a file called jest.config.js so that Jest can automatically pick it up for configuration. The file is in JS but is structured similarly to a package.json.
Make sure you input the following:
module.exports = {
testPathIgnorePatterns: ['<rootDir>/node_modules', '<rootDir>/dist'], // might want?
moduleNameMapper: {
'#components(.*)': '<rootDir>/src/components$1' // might want?
},
moduleDirectories: ['<rootDir>/node_modules', '<rootDir>/src'],
setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts'] // this is the KEY
// note it should be in the top level of the exported object.
};
Also, note that if you're using typescript you will need to make sure your jest-setup.ts file is compiled (so add it to src or to the list of items to compile in your tsconfig.json.
At the top of jest-setup.ts/js (or whatever you want to name this entrypoint) file: add import '#testing-library/jest-dom';.
You may also want to make sure it actually runs so put a console.log('hello, world!');. You also have the opportunity to add any global functions you'd like to have available in jest such as (global.fetch = jest.fn()).
Now you actually have to install #testing-library/jest-dom: npm i -D #testing-library/jest-dom in the console.
With those steps you should be ready to use jest-dom:
Without TS: you still need:
npm i -D #testing-library/jest-dom
Creating a jest.config.js and adding to it a minimum of: module.exports = { setupFilesAfterEnv: ['<rootDir>/[path-to-file]/jest-setup.js'] }.
Creating a [path-to-file]/jest-setup.js and adding to it: import '#testing-library/jest-dom';.
The jest-setup file is also a great place to configure tests like creating a special renderWithProvider( function or setting up global window functions.
None of the answers worked for me because I made the silly mistake of typing toBeInDocument() instead of toBeInTheDocument(). Maybe someone else did the same mistake :)
I had a hard time solving that problem so I believe it's important to note the followings if you're using CREATE REACT APP for your project:
You DO NOT need a jest.config.js file to solve this, so if you have that you can delete it.
You DO NOT need to change anything in package.json.
You HAVE TO name your jest setup file setupTests.js and have it under the src folder. It WILL NOT work if your setup file is called jest.setup.js or jest-setup.js.
install required packages
npm install --save-dev #testing-library/jest-dom eslint-plugin-jest-dom
create jest-setup.js in the root folder of your project and add
import '#testing-library/jest-dom'
in jest.config.js
setupFilesAfterEnv: ['<rootDir>/jest-setup.js']
TypeScript only, add the following to the tsconfig.json file. Also, change .js extension to .ts.
"include": ["./jest-setup.ts"]
toBeInTheDocument() and many similar functions are not part of the React-testing-library. It requires installing an additional package.
For anyone out there that like is trying to run tests in Typescript with jest and is still getting the same error even after installing #testing-library/jest-dom and following all the other answers: you probably need to install the type definitions for jest-dom (here) with:
npm i #types/testing-library__jest-dom
or
yarn add #types/testing-library__jest-dom
You need to install them as real dependencies and not as devDependency.
I was having this issue but for #testing-library/jasmine-dom rather than #testing-library/jest-dom.
The process of setup is just a tiny bit different with jasmine. You need to set up the environment in a before function in order for the matchers to be added. I think jest-dom will go ahead and add the matchers when you first import but Jasmine does not.
import { render, screen } from '#testing-library/react';
import MyComponent from './myComponent';
import JasmineDOM from '#testing-library/jasmine-dom';
describe("My Suite", function () {
beforeAll(() => {
jasmine.getEnv().addMatchers(JasmineDOM);
})
it('render my stuff', () => {
const { getByText } = render(<MyComponent />);
const ele = screen.getByText(/something/i);
expect(ele).toBeInTheDocument();
});
});
If you are using react-script then follow the below steps
Install #testing-library/jest-dom library if not done already using
npm i #testing-library/jest-dom.
Put import "#testing-library/jest-dom/extend-expect" in setUpTest.js
If you are using jest then import the library in jest.setup.js file.
the problem already was solved, but i will comment a little tip here, you don't need to create a single file called setup just for this, you just need to specify the module of the jest-dom on the setupFilesAfterEnv option in your jest configuration file.
Like this:
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
If you're using TS
You could also add a test.d.ts file to your test directory and use a triple slash directive:
///<reference types='#testing-library/jest-dom'>
Instead of doing:
expect(queryByText('test')).toBeInTheDocument()
you can find and test that it is in the document with just one line by using
let element = getByText('test');
The test will fail if the element isn't found with the getBy call.
I developed a React Native module (wrapping an SDK) and I’m interested in creating some unit tests using mocha. I’m not very familiar with mocha, but I can’t exactly figure out how to proceed.
I have my react native module, call it react-native-mymodule which I can use in an app by doing:
npm install react-native-mymodule
react-native link react-native-mymodule
Then I can import my module with:
import MySDK from "react-native-mymodule”;
I’m trying to do a similar thing with unit tests. In my root directory I have a test/ directory which is where I want to hold all my unit tests.
My simple test file in test/sdk.tests.js
import MySDK from "react-native-mymodule”;
var assert = require('assert');
describe(‘MySDK’, function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
I’ve tried modifying a tutorial I found online on compiling modules, but haven’t had any luck. This is a file test/setup.js:
import fs from 'fs';
import path from 'path';
import register from 'babel-core/register';
const modulesToCompile = [
'react-native-mymodule’
].map((moduleName) => new RegExp(`${moduleName}`));
const rcPath = path.join(__dirname, '..', '.babelrc');
const source = fs.readFileSync(rcPath).toString();
const config = JSON.parse(source);
config.ignore = function(filename) {
if (!(/\/node_modules\//).test(filename)) {
return false;
} else {
return false;
}
}
register(config);
.babelrc in the root level of my module
{
"presets": ["flow", "react-native"],
"plugins": [
["module-resolver", {
"root": [ "./js/" ]
}]
]
}
I have a test/mocha.opts file:
--require babel-core/register
--require test/setup.js
I’m invoking mocha with: ./node_modules/mocha/bin/mocha and I get an error:
Error: Cannot find module 'react-native-mymodule'
Can anyone advise me on the best way to test react native modules?
If you want to test native modules, I suggest the following:
1. E2E Tests
Node.js standalone cannot interpret native modules. If you want to test native modules in the context of your app, you want to create e2e tests using appium/webdriverio instead of writing unit tests with mocha.
With this, you actually start an emulator with your app installed.
Resources:
http://appium.io/docs/en/about-appium/intro/?lang=de
https://medium.com/jetclosing-engineering/react-native-device-testing-w-appium-node-and-aws-device-farm-295081129790
https://medium.com/swlh/automation-testing-using-react-native-and-appium-on-ubuntu-ddfddc0c29fe
https://webdriver.io/docs/api/appium.html
2. Unit Tests
If you want to write unit tests for your native module, write them in the Language the Native Module is written in
Resources:
https://www.swiftbysundell.com/basics/unit-testing/
https://junit.org/junit5/
https://developer.apple.com/documentation/xctest
https://cmake.org/cmake/help/latest/manual/ctest.1.html
Other than that, you have to mock the modules.
https://jestjs.io/docs/en/mock-functions
https://sinonjs.org/releases/latest/mocks/
https://www.npmjs.com/package/mock-require
I'm trying to figure out how to perform dynamic import of classes in ES6 one the server side (node.js with Babel).
I would like to have some functionalities similar to what reflection offers in Java. The idea is to import all the classes in a specific folder and instanciate them dynamically.
So for example I could have multiple classes declared in a folder like the one below :
export default class MyClass {
constructor(somevar) {
this._somevar = somevar
}
//...
//some more instance level functions here
}
and then somewhere else in my app's code I could have a function that finds out all the classes in a specific folder and tries to instanciate them :
//somewhere else in my app
instanciationFunction(){
//find all the classes in a specific folder
var classFiles = glob.sync(p + '/path_to_classes/**/*.js', {
nodir: true
});
_.each(classFiles, async function (file) {
console.log(file);
var TheClass = import(file);
var instance = new TheClass();
//and then do whatever I want with that new instance
});
}
I've tried doing it with require but I get errors. Apparently the constructor cant be found.
Any idea would be greatly appreciated.
Thanks
ES module definitions are declarative, and the current direction tools are taking is the path where dependencies are determined during parse (via static analysis), waaay before any of the code is executed. This means dynamic and conditional imports go against the said path. It's not like in Node where imports are determined on execution, upon executing require.
If you want dynamic, runtime imports, consider taking a look at SystemJS. If you're familiar with RequireJS, it takes the same concept, but expands it to multiple module formats, including ES6. It has SystemJS.import which appears to do what you want, plus handles the path resolution that you're currently doing.
Alternatively, if your intention is to shed off excess code, consider using Rollup. It will analyze code for you and only include code that's actually used. That way, you don't need to manually do conditional loading.
You need to preprocess with babel, because they are not yet a part of node (for that matter, neither are static imports - node uses require).
https://github.com/airbnb/babel-plugin-dynamic-import-node
steps:
pre
npm i -D babel-cli or npm i -D babel
1
npm i -D babel-plugin-dynamic-import-node
2
.babelrc
{
"plugins": ["dynamic-import-node"]
}
ready, go!
babel-node test_import.js for babel-cli, or for raw babel:
a
(edit) package.json
"scripts": {
"pretest": "babel test_imports.js -o dist/test_imports.js",
"test": "node dist/test_imports.js"
//...
b
node test
I had the same usecase and i managed to dynamically load and instantiate default exported classes using:
const c = import("theClass.js")
const i = new c.default();
using node v16.4.0
I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:
var expect = require('expect.js');
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect. I thought I might be able to do this using the mocha.opts file:
--require ./node_modules/expect.js/index.js
But now I get the following error when running my test:
ReferenceError: expect is not defined
This seems to make sense - how can it know that the reference to expect in my tests refers to what is exported by the expect.js library?
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
"Error: Cannot find module './does-not-exist.js'"
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.
Create test/helper.js:
var expect = require("expect.js")
global.expect = expect;
and set your test/mocha.opts to:
--require test/helper
While Louis's answer is spot on, in the end I solved this with a different approach by using karma and the karma-chai plugin:
Install:
npm install karma-chai --save-dev
Configure:
karma.set({
frameworks: ['mocha', 'chai']
// ...
});
Use:
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
Thanks to Louis answer and a bit of fiddling around I sorted out my test environment references using mocha.opts. Here is the complete setup.
My project is a legacy JavaScript application with a lot of "plain" js files which I wish to reference both in an html file using script tags and using require for unit testing with mocha.
I am not certain that this is good practice but I am used to Mocha for unit testing in node project and was eager to use the same tool with minimal adaptation.
I found that exporting is easy:
class Foo{...}
class Bar{...}
if (typeof module !== 'undefined') module.exports = { Foo, Bar };
or
class Buzz{...}
if (typeof module !== 'undefined') module.exports = Buzz;
However, trying to use require in all the files was an issue as the browser would complain about variables being already declared even when enclosed in an if block such as:
if (typeof require !== 'undefined') {
var {Foo,Bar} = require('./foobar.js');
}
So I got rid of the require part in the files and set up a mocha.opts file in my test folder with this content. The paths are relative to the root folder:
--require test/mocha.opts.js
mocha.opts.js content. The paths are relative to the location of the file:
global.assert = require('assert');
global.Foo = require("../foobar.js").Foo;
global.Bar = require("../foobar.js").Bar;
global.Buzz = require("../buzz.js");
Browserify allows creating aliases and shimming modules that are not directly CommonJS compatible. Since I'd like to run my tests in node CLI, can I somehow handle those aliases and shimmed modules in node?
For example, let's say I'm aliasing ./my-super-module to supermodule and shimming and aliasing some jquery plugin ./vendor/jquery.plugin.js -> ./shims/jquery.plugin.shim.js to jquery.plugin.
As a result, I can do this in my module:
var supermodule = require('supermodule');
require('jquery.plugin');
// do something useful...
module.exports = function(input) {
supermodule.process(output)
}
Are there any practices how I could test this module in node.js/cli so that the dependencies are resolved?
You might want to use proxyquire if you plan to test this module directly in node using any cli runner.
using mocha will be something like this
describe('test', function () {
var proxyquire = require('proxyquire').noCallThru();
it('should execute some test', function () {
var myModule = proxyquire('./my-module', {
// define your mocks to be used inside the modules
'supermodule' : require('./mock-supermodule'),
'jquery.plugin': require('./jquery-plugin-mock.js')
});
});
});
If you want to test this is a real browser, you might not need to mock your aliases modules, you can use browserify to run your tests in karma directly.
If you need to mock modules in that scenario you can use proxyquireify, which will allow you to do the same but with browserify.
there is also browsyquire which is a fork of proxyquireify that I made with some extra features and a bug fix.