I am new in Jest. I tried to write test for basic function which is
export const queryValidate = (query) => {
const str = query.replace(/\s+/g, "");
const conditionsArray = [
str === "",
str === "{",
str === "}",
str === "{}",
];
if (conditionsArray.includes(true)) {
return true;
} else {
return false;
}
};
In my Jest test file like that
import { queryValidate } from "./components/QueryValidate";
console.log(queryValidate("{"));
I am getting this error message :
import { queryValidate } from "./components/QueryValidate";
SyntaxError: Cannot use import statement outside a module
I cannot understand it is about Jest error or React module error. I try a write dummy test like :test("Fake test", () => {
expect(true).toBeTruthy();
});
Its work .
Can someone help me?
I don't have enough reputation to add a comment, therefore I'm adding an answer. I faced the same issues a while back.
As Estus has mentioned in the comment, you need to change the Jest config.
You can also have a look at babel-jest and then set a babel config file/ .babelrc, along with the preset env.
Related
I'm usimg electron-react biolerplate.electron's main.js file placed in public folder.I want to add another electron file to common constants,functions.when I try to use that file it throws above error.
I want to keep main.js short .that's why I'm using another file
/public/renderer/command-executor.js
export const executeCommandWithOutput=(command)=>{
const { exec } = require('child_process');
console.log(command);
return new Promise((resolve, reject) => {
console.log('inside promise');
exec(command, (err, stdout, stderr) => {
console.log('inside execsync');
if (err) {
console.log(err);
resolve(err);
} else if (stderr) {
console.log(stderr)
resolve(stderr);
} else {
resolve(stdout);
}
});
});
}
public/main.js
const commandExecutor=require('./renderer/command-executor');
electron.ipcMain.on('launch-App',async(event,args)=>{
commandExecutor.executeCommandWithOutput(`powershell -Command "& {Start-Process -Verb runas '${playLink}'}"`);
});
The issue is that you're trying to mix the ES5 require statement with the ES6 syntax for export. The two are incompatible. You either have to use one or the other.
Assuming your ES6 implementation with babel works fine, you should use the import statement like this:
// exporting like you are at the moment (called a named export):
export const executeCommandWithOutput = (command) =>{
...
}
// importing like so:
import { executeCommandWithOutput } from './renderer/command-executor';
But if you're using require in public/main.js, your export statement should look something like this:
exports.executeCommandWithOutput = executeCommandWithOutput
and your require will remain the same.
Here's an article to help you get a better understanding of what's happening, how the export functionality works in ES5 and what you can achieve with it: https://www.sitepoint.com/understanding-module-exports-exports-node-js/
Likewise with the ES6 syntax:
https://alligator.io/js/modules-es6/
I need to use react-int outside a component and particularly inside an util file. In order to accomplish that i'am using this code https://gist.github.com/genadyp/435f4e264cb6e377836cf63bee8987d8
But i am facing an issue with eslint that fails and it does not accept using require inside a function and using a dynamic file path too.
here is eslint output:
error Unexpected require() global-require
error Calls to require() should use string literals import/no-dynamic-require
Any advice and suggestions will be greatly appreciated.
//util.js
export function formatMessage(t, locale) {
if (t=== 0 || t === 2400) {
const translations
=require(`src/locales/${locale.toLowerCase()}.json`));
const intlProvider = new IntlProvider({ locale, messages:
translations }, {});
const mes = defineMessages({
morning: {
id: 'greeting.morning',
defaultMessage: 'hello',
},
evening: {
id: 'greeting.evening',
defaultMessage: 'good evening',
},
});
const { intl } = intlProvider.getChildContext();
return t === 0 ? intl.formatMessage(mes.morning) :
intl.formatMessage(mes.evening);
}
}
You can read more about the reasoning for this rule here: https://eslint.org/docs/rules/global-require
If you are pretty sure about what you are doing you can disable the rule adding this comment before the statement: // eslint-disable-next-line global-require
So I have this Create react app (I don't really understand webpack), and I wanted to use EaselJS on this one, However the NPM counterpart of EselJS is their version 2 (BETA) and is quite unstable and undocumented - That's why I wanted to use the minified version.
I have a easeljs.min.js on my project but I don't know how to "import it".
doing `import './easeljs.min.js' seems to also generate a lot of linting issues and seems to nor work.
EDIT:
I tried using react-helmet and append it as a script tag, but it seems that react is doing something with the minified version and causes it to error. (unexpected token <)
So I was able to fix it:
I installed react-app-rewired created config-overrides.js and added this code:
module.exports = function override(config, env) {
if (!config.resolve || Object.keys(config.resolve).length === 0) {
config.resolve = {};
}
if (!config.module || Object.keys(config.module).length === 0) {
config.module = {};
}
if (!config.module.rules || config.module.rules.length === 0) {
config.module.rules = [];
}
const resolve = {
alias: {
createjs: "createjs/builds/1.0.0/createjs.js"
}
};
config.resolve = {
...config.resolve,
...resolve
};
config.module.rules.push({
test: /node_modules[/\\]createjs/,
loaders: ["imports-loader?this=>window", "exports-loader?window.createjs"]
});
return config;
};
It seems that it is an issue with createjs itself https://github.com/CreateJS/Combined/issues/12
I also ended up using this repo for createjs.
I am making an exercise with ES2015, Jest, React and I get this error:
TypeError: Property description must be an object: undefined
at defineProperties (native)
at Object.eval (<PROJECT>/node_modules/event-emitter/index.js:127:8)
After digging into it, I think it is related to the import of the nodeModule EventEmitter or by extending the class by it.
This is the code of the script file:
import EventEmitter from 'event-emitter';
import AppDispatcher from '../dispatcher/app-dispatcher';
import {
ACTION_CURSOR_POSITION_CHANGED,
ACTION_IS_DRAGGING_CHANGED
} from '../constants/actions';
let _draggingStoreInstance = null;
/**
* DraggingStore class
*/
export default class DraggingStore extends EventEmitter
{
/**
* Constructor
*/
constructor () {
// ...
The source code of the test file looks like this:
import '../unmock/dragging-store.unmock.js';
import DraggingStore from '../../src/stores/dragging-store';
describe('Dragging Store', () => {
let draggingStoreInstance = null;
beforeEach(() => {
draggingStoreInstance = DraggingStore.getInstance();
});
it('should be defined', () => {
expect(DraggingStore).toBeDefined();
expect(draggingStoreInstance).toBeDefined();
});
});
I made an extra file for excluding mocks:
jest.dontMock('../../src/stores/dragging-store.js');
jest.dontMock('../../src/dispatcher/app-dispatcher.js');
jest.dontMock('../../src/constants/actions.js');
The code itself runs smoothly in the browser after compiling, but the test engine gives the error.
I added this in my package.json:
"scripts": {
"test": "jest"
},
"jest": {
"scriptPreprocessor": "./node_modules/babel-jest",
"unmockedModulePathPatterns": [
"./node_modules/react"
],
"collectCoverage": true,
"testDirectoryName": "spec",
"moduleFileExtensions": [
"js"
],
"collectCoverageOnlyFrom": {
// All files to test
}
}
Does anyone have a clue how to get around the problem?
Thanks in advance...
Update: full source code can be found here: https://github.com/dejakob/unlease-chess
I realize this is very late, but, a lot has changed in the time you have posted this question. With Jest v19+, and assuming you are using the latest version of Babel as well, you can follow the instructions here:
http://facebook.github.io/jest/docs/webpack.html#using-with-webpack-2
since you are using modules, you will need to tell Babel to transpile them to commonjs requires so that they can be run in the node environment, which is how Jest works.
I am using Karma with mocha to test my React components. I have some warnings displayed when the PropTypes are not matched. However it would be really interesting to have these warnings to cause an actual error, as to track down the test and fix it.
Do you know how this could be achieved?
You can replace the console.warn method with your own and throw when the message provided matches a certain pattern.
let warn = console.warn;
console.warn = function(warning) {
if (/(Invalid prop|Failed propType)/.test(warning)) {
throw new Error(warning);
}
warn.apply(console, arguments);
};
Small improvements to accepted answer: console.error instead of console.warn as spain-train mentioned, added 'Failed prop type' to regex, as only then it works with React 15.3.1, and made the code more strict eslint friendly.
const error = console.error;
console.error = function(warning, ...args) {
if (/(Invalid prop|Failed prop type)/.test(warning)) {
throw new Error(warning);
}
error.apply(console, [warning, ...args]);
};
2021 update:
const consoleError = console.error;
console.error = function (...args) {
if (/(Invalid prop|Failed propType|Failed .+ type)/.test(args[0])) {
const errorMessage = args.reduce((p, c) => p.replace(/%s/, c));
throw new Error(errorMessage);
}
consoleError.apply(console, args);
};
Failed prop type is now Failed %s type: %s%s. It uses string substitutions to write to console. Here is the code in React.