Mocha test failing using babel and webpack - mocha.js

So I am using webpack, babel, and mocha here. When I have code like this:
import userImage from '../../images/user.png';
and I build with webpack, userImage results in a string to the path of the file since I am using the file loader for images (requirements call for me not to embed images) however when I try to run my mocha tests using:
./node_modules/.bin/babel-node ./node_modules/.bin/babel-istanbul cover ./node_modules/.bin/_mocha
I get a syntax error:
SyntaxError: /repositories/react-seed/web/app/images/user.png: Unexpected character '�' (1:0)
> 1 | �PNG
| ^
2 |
3 |
I also get this error when removing istanbul. So it seems like it is trying to load the actually image file however can parse it as JavaScript since it is not.
Anyone know a way around this issue?

You can use the --compilers option which allows you to customize the nodejs require system in order to let it understand png files. So :
mocha --compilers png:./mochacfg.js
Or create a file 'test/mocha.opts' containing (better for your needs):
--compilers png:./mochacfg.js
With ./mochacfg.js:
require.extensions['.png'] = function(){ return null; }
This ignores png files (should be ok if you do nothing special with them).
If you want to do something with the image data:
var fs = require('fs');
require.extensions['.png'] = function(module, filepath) {
var src = fs.readFileSync(filepath).toString ('base64');
return module._compile('module.exports = "data:image/png;base64,' + src + '";');
}

Its quite late to answer this question but just for knowledge sharing purpose, I am answering another approach to do this.
Create a test-config.js file and use it while running the mocha test cases.
var jsdom = require('jsdom').jsdom;
process.env.NODE_ENV = 'test';
// -------------------------------
// Disable webpack-specific features for tests since
// Mocha doesn't know what to do with them.
['.css', '.scss', '.png', '.jpg'].forEach(ext => {
require.extensions[ext] = () => null;
});
and inside package.json use this test command to run the test cases
"test": "mocha ./test/test-setup.js './test/**/*.spec.js' --compilers js:babel-core/register",
I hope it helps someone.

Related

Can't get tagging to work with cypress-cucumber-preprocessor

I am currently having issues with using tagging with the cypress-cucumber-preprocessor package. I know that the cypress-tags has been removed and made redundant so I'm trying to set up tagging using the new syntax but to no avail.
Here is my feature:
Feature: duckduckgo.com
Rule: I am on a desktop
Scenario: visiting the frontpage
When I visit <site>
Then I should see a search bar
#google
Examples:
| site |
| google.com |
#duckduckgo
Examples:
| site |
| duckduckgo.com |
And my step definitions:
import { When, Then } from "#badeball/cypress-cucumber-preprocessor";
When(`I visit` + url, () => {
if(url === 'duckduckgo.com') return cy.visit("https://www.duckduckgo.com");
if(url === 'google.com') return cy.visit("https://www.google.com");
});
Then("I should see a search bar", () => {
cy.get("input").should(
"have.attr",
"placeholder",
"Search the web without being tracked"
);
});
When I try to run my tests with npx cypress run --env tags="#google", it gives me an error saying url in my steps definitions isn't defined. What am I doing wrong?
Try to add script with this command in package.json file this way:
"scripts": {
"open:test": "npm run clean:report && cypress open --env configFile=test,TAGS=#test" (or any tag you need)
}
And then use it as:
npn run open:test
The main difference besides rapping it into script is not using quotes, maybe this will help you

react-i18next cannot resolve key

I have a problem with react-i18next not resolving my keys, so everything I get as an output are the keys themself.
I had to embed my project as gui project to a VisualStudio solution. Running my original project works just fine, the solution project in contrast cannot resolve the key part of my translate function call.
t('user:KEY_CONSTANT') //output: KEY_CONSTANT
My i18n.config looks like this:
i18n
.use(XHR)
.init({
lng: i18nHelper.languageDetector(),
load: 'currentOnly',
fallbackLng: 'en-US',
backend: {
loadPath: 'i18n/{{lng}}/{{ns}}.json'
},
ns: ['admin', 'user'],
defaultNS: 'admin',
debug: false,
interpolation: {
escapeValue: false,
formatSeparator: ',',
format: function (vale, format, lng) {
if (format === 'uppercase') return value.toUpperCase();
return value;
}
}
});
When embedding the project in the solution, I had to change webpacks output folder, which I think is the actual reason of malfunctioning, but I can't find where exact the problem occurs. I tried changing the loadPath, but if thats the source of failure, I just didn't try it the right way :S
My project tree looks like:
Solution
|-gui
| |-src
| |-i18n
| |-de-DE(containing the german admin.json and user.json files)
| |-en-US(containing the english admin.json and user.json files)
| |-utils
| |-i18n.js
|-out
| |-prgFiles
| |-html
| |-i18n(contains same items as i18n under src)
In my old project, the webpack output was '/dist/' on the same level as src, in the solution, '../out/prgFiles/html'.
admin.json right now contains no keys at all, user.json contains the keys just like you'd expect:
{
"KEY_CONSTANT": "Actual string value"
}
As said, I tried around a bit with path changes, checked for translate, i18next and i18next-Provider beeing found and everythings fine. It just cant resolve KEY_CONSTANT to the actual value.
Do you have an idea what the problem might be?
set debug option to true in i18next init -> i bet you will get an error stating something like backendConnector failed to load namespace user...
make sure the clientside is able to load the translations (the webpack-dev server does a good job in doing so - but in production you will need to serve those file yourself)

Gulp error: Path must be a string

I've got a problem with gulp.js.
Steps to reproduce:
$ composer global require "laravel/installer=~1.1"
$ laravel new myproject
$ cd myproject
$ php artisan serve
$ npm install
$ npm rm bootstrap-sass —save
$ npm install foundation-sites —save
$ npm install motion-ui —save
then I copy
_settings.scss
from
node_modules/foundation-sites/scss/settings
to
resources/assets/sass
in app.scss then i put every Foundation import
and finally I write Elixir task as reported here:
http://zecipriano.com/en/2015/12/laravel-elixir-and-zurb-foundation-revisited/
But when I launch gulp from terminal:
path.js:7
throw new TypeError('Path must be a string. Received ' + inspect(path));
... don't know what to do.
Everything updated, so I think it's not a version problem.
[EDIT]
$ node -v
v6.8.0
and here's my gulpfile.js:
const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
// Sass
var options = {
includePaths: [
'node_modules/foundation-sites/scss',
'node_modules/motion-ui/src'
]
};
mix.sass('app.scss', null, options);
// Javascript
var jQuery = '../../../node_modules/jquery/dist/jquery.js';
var foundationJsFolder = '../../../node_modules/foundation-sites/js/';
mix.scripts([
jQuery,
foundationJsFolder + 'foundation.core.js',
// Include any needed components here. The following are just examples.
foundationJsFolder + 'foundation.util.mediaquery.js',
foundationJsFolder + 'foundation.util.keyboard.js',
foundationJsFolder + 'foundation.util.timerAndImageLoader.js',
foundationJsFolder + 'foundation.tabs.js',
// This file initializes foundation
'start_foundation.js'
]);
});
Any ideas?
Thank you in advance.
The problem is that the options have been moved from the third to the fourth parameter. You can run it with:
mix.sass('app.scss', null, null, options);
Cheers :D
I have the node 4.4.2 installed and countered the same error. Then I passed the the directory string directly instead of using an array with directions.

Can you run multiple instances of webpack at once?

Let's say I have an array of components, that need to spit out their own source, as they wont always be included together, it needs to be it's own bundle. The idea is that there will eventually be 100's of components, and they can be cherry picked whenever.
However, when using webpack-stream with gulp, even though I'm dynamically registering the tasks, and that I can see they're running sequentially, it only runs one webpack stream by the looks of it, but seems to output it's bundle from the SECOND component, into the first components directory.
It's a pretty simple build process, it's an array of components like so:
var components = [
{'name : 'a', src : './foo/bar/entrya.js', dest : '/dir/a'},
{'name : 'b', src : './foo/bar/entryb.js', dest : '/dir/b'},
];
Relatively simple right? Then to register the tasks, it's something like this:
components.forEach(component => {
gulp.task(component.name, cb => {
function task(component) {
return gulp.src(component.src)
.pipe($.webpackStream(webpackConfig))
.pipe(component.dest(component.dest));
}
return task.apply(this, [component, cb]);
});
});
This is an incredibly dumbed down version of what I have, but it's pretty much the same thing, dynamically generates and then later on we run those tasks sequentially.
webpack-stream can handle multiple entry points and multiple builds per multiple entry points.
var gulp = require('gulp');
var webpack = require('webpack-stream');
gulp.task('build', function() {
return gulp.src(['src/entry.js']) // entry.js file doesn't need to exist
.pipe(webpack({
entry: {
a : __dirname + "/foo/bar/entrya.js",
b : __dirname + "/foo/bar/entryb.js"
},
output: {
filename: '[name].js'
}
}))
.pipe(gulp.dest('dir/'));
});
Your build is not running in parallel. you are just sequentially registering tasks. However you can run those tasks in parallel as child processes. One good option you can use is parallel-webpack.

`Invalid mapping` error trying to use babel require hook and polyfill with react jsx transpile

I'm trying to use babel for both ES6 and JSX transpilation for mocha tests.
Suppose we have test.jsx like this:
var React = require("react");
React.createClass({
render: function(){
return (<div>Hello World</div>);
}
});
Running babel test.jsx gives us valid transformed code. No problem.
I would expect that if I create a test.js file like this:
require("babel/register");
require("./test.jsx");
And then run node test.js, it would transpile my jsx for me in line, but instead I get an error:
c:\Users\user\dev\app\node_modules\babel\node_modules\babel-core\lib\babel\t
ransformation\file\index.js:628
throw err;
^
Error: c:/Users/user/dev/app/test.jsx: Invalid mapping: {"generated":{"line"
:6,"column":11},"source":"c:/Users/user/dev/app/test.jsx","name":null}
at SourceMapGenerator_validateMapping [as _validateMapping] (c:/Users/user/dev/app/node_modules\babel\node_modules\source-map\lib\source-map\source-map-
generator.js:275:15)
at SourceMapGenerator_addMapping [as addMapping] (c:/Users/user/dev/app/
node_modules\babel\node_modules\source-map\lib\source-map\source-map-generator.j
s:105:14)
at SourceMap.mark (c:/Users/user/dev/app/node_modules\babel\node_modules
\babel-core\lib\babel\generation\source-map.js:65:9)
at CodeGenerator.print (c:/Users/user/dev/app/node_modules\babel\node_mo
dules\babel-core\lib\babel\generation\index.js:236:16)
at NodePrinter.plain (c:/Users/user/dev/app/node_modules\babel\node_modu
les\babel-core\lib\babel\generation\node\printer.js:16:27)
at CodeGenerator.ReturnStatement (c:/Users/user/dev/app/node_modules\bab
el\node_modules\babel-core\lib\babel\generation\generators\statements.js:120:13)
at CodeGenerator.print c:/Users/user/dev/app/node_modules\babel\node_mo
dules\babel-core\lib\babel\generation\index.js:238:22)
at NodePrinter.plain (c:/Users/user/dev/app/node_modules\babel\node_modu
les\babel-core\lib\babel\generation\node\printer.js:16:27)
at CodeGenerator.printJoin (c:/Users/user/dev/app/node_modules\babel\nod
e_modules\babel-core\lib\babel\generation\index.js:286:13)
at NodePrinter.sequence (c:/Users/user/dev/app/node_modules\babel\node_m
odul
es\babel-core\lib\babel\generation\node\printer.js:23:27)
According to the docs, it looks like this should work. Am I missing something obvious, or should I report this as a bug in babel?
This was a bug in acorn-jsx, the JSX parser that Babel uses. The recommended fix would be:
rm -rf node_modules/babel && npm install

Resources