Jest can't transpile node_modules - unit-testing

I am having the following error when running Jest
SyntaxError: node_modules/my_styleguide/src/components/blocks/SegmentSetting.jsx: Unexpected token (46:10)
44 | ) {
45 | return (
> 46 | <p className="SettingDescr">{self.props.description}</p>
| ^
47 | )
48 | }
49 | }
The node_modules dependency is still in its es6 format. Jest doesn't seem to provide the option to transpile your node_modules, as it does with your actual app. Instead, jest ignores the node_modules folder.
The .bashrc file looks ok to me:
{
"presets": ["es2015", "react", "stage-0"]
}
How do you make Jest transpile your node_modules too? It would be the equivalent of the "--ignore false" flag that we have in mocha.

I would mark this as an answer rather than the answer.
I had a similar issue, multiple components in node_modules in ES2015 and in need of transpilation.
I updated transformIgnorePatterns to:
["/node_modules/(?!(our-react-components-.*?\\.js$))"]
The negative look-ahead for modules in our-react-components-* folders mean Jest (and therefore Babel) will find and transpile our shared components.
This was in an ejected Create React App project with Jest 20.0.4.

Related

Unable to load strapi instance in unit testing

I am trying to run test cases for strapi but it is not allowing me to do so. I am using postgres database.
I have checked other answers and I have only one database.js file and not database.json
The error I get-
lerna ERR! yarn run test:local stderr:
● process.exit called with "1"
7 | async function setupStrapi() {
8 | if (!instance) {
> 9 | instance = await Strapi().load();
| ^
10 | await instance.app
11 | .use(instance.router.routes()) // populate KOA routes
12 | .use(instance.router.allowedMethods()); // populate KOA methods
at Strapi.stop (../../node_modules/strapi/lib/Strapi.js:316:13)
at Strapi.stopWithError (../../node_modules/strapi/lib/Strapi.js:302:17)
at ../../node_modules/strapi-connector-bookshelf/lib/mount-models.js:688:18
at module.exports (../../node_modules/strapi-connector-bookshelf/lib/mount-models.js:708:7)
at mountConnection (../../node_modules/strapi-connector-bookshelf/lib/index.js:84:7)
at async Promise.all (index 0)
at Object.initialize (../../node_modules/strapi-database/lib/connector-registry.js:30:9)
at DatabaseManager.initialize (../../node_modules/strapi-database/lib/database-manager.js:43:5)
at Strapi.load (../../node_modules/strapi/lib/Strapi.js:362:5)
at setupStrapi (tests/helpers/setup.js:9:16)
error Command failed with exit code 1.
Any leads to fix this?

vue cli 3 - ProvidePlugin doesn't work (vue.config.js)

I am trying to add webpack.ProvidePlugin which isn't working on Vue-cli 3.
I also tried to set lodash as a global import (so I won't have to import it in each store module).
vue.config
const webpack = require("webpack");
module.exports = {
configureWebpack: {
plugins: [new webpack.ProvidePlugin({ _: "lodash" })]
}
};
build Error:
Module Warning (from ./node_modules/eslint-loader/index.js):
error: '_' is not defined (no-undef) at src/store/modules/templates.js:24:10:
22 | export default Object.assign({}, base, {
23 | namespaced: true,
> 24 | state: _.cloneDeep(initialState),
| ^
25 | mutations: {
26 | addTemplate(state, template) {
27 | if (!template) throw new Error("template is missing");
I built the project after adding the lines to vue.config and they gave me the aforementioned error.
The issue doesn't seem to be with Vue CLI but with eslint. See this question for a similar issue (just replace d3 with _): Webpack not including ProvidePlugins
In short, adding this to your eslint config (often found in .eslintrc.js) should make it work:
"globals": {
"_": true
}

Unit testing in vuejs

I am trying to configure/run my first unit test for Vuejs. But I can't get past the configuration issues. I have tried installing the libraries but for some reason I keep getting errors.
Here is what an example of my code looks like:
My directory structure:
hello/
dist/
node_modules/
src/
components/
hello.vue
test/
setup.js
test.spec.js
.babelrc
package.json
webpack.config.js
Contents inside my files
src/components/hello.vue
<template> <div> {{message}} </div> </template>
<script>
export default {
name: 'hello',
data () { return message: 'Hi' },
created () {
// ...
}
}
test/setup.js
// setup JSDOM
require('jsdom-global')()
// make expect available globally
global.expect = require('expect')
test/test.spect.js
import { shallow } from 'vue/test-utils'
import { hello} from '../../../src/components/hello.vue'
describe('hello', () => {
// just testing simple data to see if it works
expect(1).toBe(1)
})
.babelrc
{
"env": {
"development": {
"presets": [
[
"env",
{
"modules": false
}
]
]
},
"test": {
"presets": [
[
"env",
{
"modules": false,
"targets": {
"node": "current"
}
}
]
],
"plugins": [
"istanbul"
]
}
}
}
package.json
...
"scripts": {
"build": "webpack -p",
"test": "cross-env NODE_ENV=test nyc mocha-webpack --webpack-config webpack.config.js --require test/setup.js test/**/*.spec.js"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"vue-loader": "^13.5.0",
"vue-template-compiler": "^2.5.9",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7",
"jsdom": "^11.3.0",
"jsdom-global": "^3.0.2",
"mocha": "^3.5.3",
"mocha-webpack": "^1.0.0-rc.1",
"nyc": "^11.4.1",
"expect": "^21.2.1",
"#vue/test-utils": "^1.0.0-beta.12"
},
...
"nyc": {
"include": [
"src/**/*.(js|vue)"
],
"instrument": false,
"sourceMap": false
}
and finally my webpack.config.js
...
if(process.env.NODE_ENV == "test") {
module.exports.externals = [ require ('webpack-node-externals')()]
module.exports.devtool = 'inline-cheap-module-source-map'
}
now when I run npm test from my root folder hello/ I get this error:
> hello#1.0.0 test C:\Users\john\vue-learn\hello
> npm run e2e
> hello#1.0.0 e2e C:\Users\john\vue-learn\hello
> node test/e2e/runner.js
Starting selenium server... started - PID: 12212
[Test] Test Suite
=====================
Running: default e2e tests
× Timed out while waiting for element <#app> to be present for 5000 milliseconds. - expected "visible" but got: "not found"
at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
FAILED: 1 assertions failed (20.281s)
_________________________________________________
TEST FAILURE: 1 assertions failed, 0 passed. (20.456s)
× test
- default e2e tests (20.281s)
Timed out while waiting for element <#app> to be present for 5000 milliseconds. - expected "visible" but got: "not found"
at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello#1.0.0 e2e: `node test/e2e/runner.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello#1.0.0 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\john\AppData\Roaming\npm-cache\_logs\2018-04-03T23_53_15_976Z-debug.log
npm ERR! Test failed. See above for more details.
I don't know why this happens. When I installed my webpack project at first I didn't install a testing library with the npm init command so there are no conflicts, but still I get that error:
update (after bounty)
I'm just trying to test my vuejs application. Hopefully with jasmine/karma. If anyone knows how to integrate these into a simple app and run the firsts test, I can take it from there. My problem is not writing tests but configuring it
So first thing you didn't need to enable the end to end testing in your project. I would say start fresh
$ npm install -g vue-cli
$ vue init webpack vue-testing
? Project name vue-testing
? Project description A Vue.js project
? Author Tarun Lalwani <tarun.lalwani#payu.in>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner karma
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) yarn
Say N to Setup e2e tests with Nightwatch and use Karma for the Pick a test runner.
$ npm test
> vue-testing#1.0.0 test /Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/vue-testing
> npm run unit
> vue-testing#1.0.0 unit /Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/vue-testing
> cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run
07 04 2018 21:35:28.620:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
07 04 2018 21:35:28.629:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
07 04 2018 21:35:28.645:INFO [launcher]: Starting browser PhantomJS
07 04 2018 21:35:32.891:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket M1HeZIiOis3eE3mLAAAA with id 44927405
HelloWorld.vue
✓ should render correct contents
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 SUCCESS (0.061 secs / 0.041 secs)
TOTAL: 1 SUCCESS
=============================== Coverage summary ===============================
Statements : 100% ( 2/2 )
Branches : 100% ( 0/0 )
Functions : 100% ( 0/0 )
Lines : 100% ( 2/2 )
================================================================================
Now your npm test would work fine.
According to the error logs you provide here, the failing tests that you spot are the End to End ones. Indeed, by executing the command npm test e2e you're testing using Nightwatch. See under /tests/e2e/specs. Here you should have a default test file checking that your Vue application properly create a DOM element identified as app.
The test should be the following:
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function (browser) {
// automatically uses dev Server port from /config.index.js
// default: http://localhost:8080
// see nightwatch.conf.js
const devServer = browser.globals.devServerURL
browser
.url(devServer)
.waitForElementVisible('#app', 5000)
.assert.elementPresent('.hello')
.assert.containsText('h1', 'Welcome to Your Vue.js App')
.assert.elementCount('img', 1)
.end()
}
}
In your case this test is failing because you have probably removed the file named App.vue that is generated through vue-cli scaffolding. The error you get is because the above test checks, with a 5 seconds timeout, if a DOM node named "app" is rendered (i.e.: .waitForElementVisible('#app', 5000)).
Basically it is failing because you actually do not provide this div in your application anymore (due of App.vue removal, maybe).
So you have two options here:
restoring the App.vue file (i.e.: create a div identified as 'app' where you mount a Vue instance);
editing the end to end according to your needs.
Hope this helps!

How can I speed up development builds while developing a linked package? (Ember/Broccoli)

My Broccoli builds take up a LOT of time. ~30 seconds to build every time I change a line of js (I mean the incremental re-builds with dev server running, NOT a complete build).
Here's my situation. I have project A which is an ember addon to project B which I npm link in. As I'm developing project A, I am running ember server on project B.
EVERY SINGLE TIME that I make a change to a line of javascript in project A and rebuild, I see that the following files change in project B:
B/dist/assets/vendor.css
B/dist/assets/vendor.js
B/dist/assets/vendor.map
B/dist/assets/B.css
B/dist/assets/B.css.map
My concern is that, because I'm developing a linked package, my broccoli configuration is such that the entire node_modules is recombined into those vendor files.
Is there a way for me to configure ember/broccoli to use a separate file to compile A into and segregate it from the rest of vendor.js? B/dist/assets/A.min.css and B/dist/assets/A.min.js for example?
...or I'm a guessing at the cause of the problem incorrectly?
Thank you so much for your help in advance!
Edit: Here's some extra info as requested
Slowest Nodes (totalTime => 5% ) | Total (avg)
----------------------------------------------+---------------------
Concat (11) | 39239ms (3567 ms)
RecastFilter (280) | 33127ms (118 ms)
Babel (233) | 14099ms (60 ms)
EslintValidationFilter (5) | 12632ms (2526 ms)
LessCompiler (46) | 7191ms (156 ms)
Slowest Nodes (totalTime => 5% ) | Total (avg)
----------------------------------------------+---------------------
SourceMapConcat: Concat: Vendor /asset... (1) | 36270ms
LessCompiler (46) | 4029ms (87 ms)
Here's the index.js (Of project A):
const EngineAddon = require('ember-engines/lib/engine-addon');
const TreeMerger = require('broccoli-merge-trees');
const LessCompiler = require('broccoli-less-single');
const Funnel = require('broccoli-funnel');
const path = require('path');
module.exports = EngineAddon.extend({
name: 'ember-engine-admin-ui',
lazyLoading: false,
treeForVendor(tree) {
let addonTree = this.treeGenerator(path.resolve(this.root, this.options.trees.addon));
let compiledLessTree = new LessCompiler(addonTree, 'styles/addon.less', `styles/${this.name}.css`);
let sidebarCSSTree = new Funnel(path.dirname(require.resolve('sidebar-v2/css/leaflet-sidebar.css')), {
files: ['leaflet-sidebar.css'],
destDir: 'styles'
});
let sidebarJSTree = new Funnel(path.dirname(require.resolve('sidebar-v2/js/leaflet-sidebar.js')), {
files: ['leaflet-sidebar.js'],
destDir: 'js'
});
return new TreeMerger([tree, compiledLessTree, sidebarCSSTree, sidebarJSTree]);
},
included() {
this._super.included.apply(this, arguments);
this.import(`vendor/styles/${this.name}.css`);
this.import('vendor/js/leaflet-sidebar.js');
this.import('vendor/styles/leaflet-sidebar.css');
},
isDevelopingAddon() {
return true;
}
});

Grails - Apache Tika plugin test-app failure

I'm learning how to use the Apache Tika plugin. I've just copied the code from github and I get failure error when unit testing.
This is the unit test
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
* Test for tikaService: try to parse test data.
*/
#TestFor(TikaService)
class TikaServiceSpec extends Specification {
def 'Parse a word file to XML'() {
given:
def file = new File('parserTest.doc')
when:
def xml = service.parseFile(file)
then:
def doc = new XmlSlurper().parseText(xml)
doc.body.p.find{
it.text() == 'This is a simple test document'
}
}
}
This is the error I get.
Running 5 unit tests... 8 of 8
| Failure: Parse a word file to XML(com.myApp.TikaServiceSpec)
| Condition not satisfied:
doc.body.p.find{ it.text() == 'This is a simple test document' }
| | | |
| | | groovy.util.slurpersupport.NoChildren#4c2a4e84
| | Tika Parser Test
| | This is a simple test document
| Tika Parser Test
| This is a simple test document
Tika Parser Test
This is a simple test document
at com.myApp.TikaServiceSpec.Parse a word file to XML(TikaServiceSpec.groovy:21)
What am I doing wrong?
dependencies {
compile('org.apache.tika:tika-core:0.7')
compile('org.apache.tika:tika-parsers:0.7') { excludes "xercesImpl", "xmlParserAPIs", "xml-apis", "log4j" }
}
Thanks to #Gagravarr, the problem has been solved. I used the version 1.12 and it worked.
The repo is https://repo1.maven.org/maven2/org/apache/tika/