Configure phantomjs to work with webpack and karma nwb - node.js

I am using nwb to configure a react app, I would use like to chai and enzyme to set up my testing environment. I have made the following changes to accomplish this, I created a tests.webpack.js file:
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import chaiAsPromised from 'chai-as-promised';
import sinonChai from 'sinon-chai';
chai.use(chaiEnzyme());
chai.use(chaiAsPromised);
chai.use(sinonChai);
const context = require.context('./src', true, /\.spec\.js/);
context.keys.forEach(context);
I also modified the karma config in nwb.config.js:
const karmaChaiPlugins = require('karma-chai-plugins');
module.exports = {
type: 'react-component',
npm: {
esModules: true,
umd: {
global: 'ReactMg',
externals: {
react: 'React',
},
},
},
karma: {
testContext: 'tests.webpack.js',
plugins: [
karmaChaiPlugins,
],
frameworks: ['mocha', 'chai', 'chai-as-promised'],
},
webpack: {
compat: {
enzyme: true,
sinon: true,
},
},
};
I get an error when running nwb test after defining index.spec.js in src:
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
TypeError: undefined is not a function (evaluating 'context.keys.forEach(context)')
at tests.webpack.js:73
PhantomJS 2.1.1 (Linux 0.0.0): Executed 0 of 0 ERROR (0.375 secs / 0 secs)
Karma exit code was 1

To fix error TypeError: undefined is not a function
You should change context.keys.forEach(context); on context.keys().forEach(context); because keys is function[1]
[1] - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Related

Using node polyfills in a es module that is imported into angular: Buffer is not defined

I want to create an ES module which can be easily imported in a frontend environment (in my test case angular). However I have a commonjs module in my dependencies which uses some node functionalities. At the current state my module is only usable if there are some polyfills defined within angular (I found them here: global, buffer, process ):
// in polyfills.ts
(window as any).global = window;
global.Buffer = global.Buffer || require("buffer").Buffer;
import * as process from "process";
window["process"] = process;
My goal is to build my module in a way that nothing needs to be done on the frontend side except installing the package. For this I want to move the polyfill part down a level to my module.
To reach this goal I am trying to bundle my module using webpack and defining the polyfills there. This is my current config:
import path from "path";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import webpack from "webpack";
const require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
entry: "./src/index.ts",
module: {
rules: [
{
test: /\.ts?$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
plugins: [
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
}),
],
resolve: {
fallback: {
buffer: require.resolve("buffer"),
process: require.resolve("process"),
},
extensionAlias: {
".js": [".ts", ".js"],
".mjs": [".mts", ".mjs"],
},
},
experiments: {
outputModule: true,
},
output: {
path: path.resolve(__dirname, "dist"),
library: {
type: "module",
},
},
};
Webpack runs this config without errors (only with size related warnings) but when I include the bundle into angular and remove the buffer polyfill there I still get the runtime error Buffer is not defined (chrome).
Is this a minor error in my config or did I miss something
important which makes my whole approach unreasonable?

Migrating cypress test from old version to latest version throws error

I am trying to migrate my test from Cypress 8.7.0 version to Cypress 10.10.0 version. Installed the latest version and did the below settings, but getting below error.
Using below versions:
Cypress 10.10.0,
"#badeball/cypress-cucumber-preprocessor": "^11.4.0",
node v18.4.0,
#bahmutov/cypress-esbuild-preprocessor": "^2.1.5"
Expected to find a global registry (this usually means you are trying to define steps or hooks in support/e2e.js, which is not supported) (this might be a bug, please report at https://github.com/badeball/cypress-cucumber-preprocessor)
Because this error occurred during a before each hook we are skipping all of the remaining tests.
I have added the error handling in e2e.js file and support/index.js file but still could not resolve this issue. I have .env file which has the environment variable in my root location. Could someone please advise on this issue ?
//Detail error log:
Because this error occurred during a `before each` hook we are skipping all of the remaining tests.
at fail (tests?p=tests/cypress/e2e/login/loginBase.feature:964:15)
at assert (tests?p=tests/cypress/e2e/login/loginBase.feature:971:9)
at assertAndReturn (tests?p=tests/cypress/e2e/login/loginBase.feature:975:9)
at getRegistry (tests?
Cypress version : v10.10.0
//tests/cypress/e2e/login/login.feature
#regression
#login
Feature: Login to base url
Scenario: Login to base url
Given I go to base url
//step defintion:
tests/cypress/stepDefinitions/login.cy.js
import { Given, When, Then, Before, After, And } from "#badeball/cypress-cucumber-preprocessor";
When('I go to base url', () => {
cy.visit(Cypress.config().baseUrl);
})
// tests/cypress/support/index.js file
// Import commands.js using ES2015 syntax:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
});
//tests/cypress/support/e2e.js
// Import commands.js using ES2015 syntax:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
})
//.cypress-cucumber-preprocessorrc.json // add this file in project root location
{
"stepDefinitions": [
"[filepath].{js,ts}",
"tests/cypress/stepDefinitions/**/*.{js,ts}"
]
}
// cypress.config.js
const { defineConfig } = require('cypress')
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin = require("#badeball/cypress-cucumber-preprocessor")
const createEsbuildPlugin = require("#badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;
const dotenvPlugin = require('cypress-dotenv');
async function setupNodeEvents(on, config) {
await addCucumberPreprocessorPlugin.addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
createBundler({
plugins: [createEsbuildPlugin(config)],
})
);
//webpack config goes here if required
config = dotenvPlugin(config)
return config;
}
module.exports = defineConfig({
e2e: {
baseUrl: 'https://bookmain.co',
apiUrl: 'https://bookmain.co/api/books/',
specPattern: "tests/cypress/e2e/**/*.feature",
supportFile: false,
setupNodeEvents
},
component: {
devServer: {
framework: "next",
bundler: "webpack",
},
},
});
// package.json
"cypress-cucumber-preprocessor": {
"nonGlobalStepDefinitions": true,
"stepDefinitions": "tests/cypress/stepDefinitions/**/*.{js,ts}",
"cucumberJson": {
"generate": true,
"outputFolder": "tests/cypress/cucumber-json",
"filePrefix": "",
"fileSuffix": ".cucumber"
}
},
In cypress.config.js add the following:
const {dotenvPlugin} = require('cypress-dotenv');
module.exports = (on, config) => {
config = dotenvPlugin(config)
return config
}
This will resolve the issue.

How can I debug this Webpack error - ERROR in bundle.js from Terser

I am trying to use webpack to bundle up a Node JS project, for the benefits it offers in terms of minimising the size of the code etc. and bundling together all of the dependencies.
My webpack job is failing with the following error:
ERROR in bundle.js from Terser
Invalid function parameter [bundle.js:186393,23]
This is my webpack.config file:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
target: "node",
mode: "production",
entry: {
app: ["./src/vitaq_client.js"]
},
// https://webpack.js.org/configuration/node/
// node: {
// global: false,
// __filename: true,
// __dirname: true,
// },
module: {
// https://github.com/ivan-aksamentov/reactlandia-bolerplate-lite/issues/5#issuecomment-413306341
exprContextCritical: false,
rules: [
{
test: /\.node$/,
use: 'node-loader'
},
{
test: /coffee/,
use: 'node-loader'
},
{
test: /\.coffee$/,
use: [ 'coffee-loader' ]
},
// {
// test: /\.map$/,
// use: ["source-map-loader"],
// enforce: "pre"
// },
]
},
plugins: [
new CleanWebpackPlugin(),
],
output: {
path: path.resolve(__dirname, "./build"),
filename: "bundle.js"
},
};
and this is the command I am using to run it:
webpack --config webpack.config.js
From the searching I have done it seems that there is a Terser plugin for code minification, but as you can see from my config file I am not loading that plugin, so does webpack use that plugin by default? If not how could I be getting an error from Terser ?
If I set the mode to "development" in the config file, then I do not get the problem, but I suspect that is because development code would not get minified.
I am a bit stuck as to how I set about debugging this problem - are there ways of getting more output from Webpack. I have tried using the --json > compilation-stats.json command line argument when I invoke webpack, but I get a huge output file (43Mb) and I can't find anything in all of that to help.
Any suggestions would be gratefully received.
This is an error with assignment where you have an invalid function parameter at the given line of bundle.js.
You can solve this by not minimizing the webpack build:
optimization: {
minimize: false
}
Then finding the assignment error line from the error output, in the non minified bundle.
Invalid function parameter [bundle.js:186393,23]
Hope this helps someone else.

SpecReporter is not a constructor error on jasmine

I try to configure simple project on jasmine using node.js. I got following files:
/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'**/*.testdev.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'foo',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 60000,
print: function() {}
},
useAllAngular2AppRoots: true,
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e'
});
},
onPrepare: function() {
jasmine.getEnv().addReporter(new SpecReporter());
}
};
Then a test file:
import {} from 'jasmine';
describe ("test", function() {
it ("should work", function() {
console.log('============ Main Workflow file starts');
});
});
And I receive error when I'm running npm test:
C:\newcheckproject>npm test
> newcheck#1.0.0 test C:\\newcheckproject
> protractor
(node:7492) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[12:47:12] I/launcher - Running 1 instances of WebDriver
[12:47:12] I/direct - Using ChromeDriver directly...
[12:47:15] E/launcher - Error: TypeError: SpecReporter is not a constructor
at onPrepare (C:\Users\OSP\WebstormProjects\newcheckproject\protractor.conf.js:30:38)
at q_1.Promise (C:\Roaming\npm\node_modules\protractor\lib\util.ts:48:39)
at Function.promise (C:\Roaming\npm\node_modules\protractor\node_modules\q\q.js:682:9)
at Object.runFilenameOrFn_ (C:\Roaming\npm\node_modules\protractor\lib\util.ts:39:10)
at plugins_.onPrepare.then (C:\Roaming\npm\node_modules\protractor\lib\runner.ts:103:21)
at _fulfilled (C:\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54)
at self.promiseDispatch.done (C:\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30)
at Promise.promise.promiseDispatch (C:\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13)
at C:\Roaming\npm\node_modules\protractor\node_modules\q\q.js:556:49
at runSingle (C:\Roaming\npm\node_modules\protractor\node_modules\q\q.js:137:13)
[12:47:15] E/launcher - Process exited with error code 100
npm ERR! Test failed. See above for more details.
All answers says that I should replace in the protractor file a line: var SpecReporter = require('jasmine-spec-reporter');, but I do have it. What might also a problem here?
Since 3.0.0, jasmine-spec-reporter module exports SpecReporter and DisplayProcessor.
According to the documentation, you need to configure it like this:
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
jasmine.getEnv().addReporter(new SpecReporter());

Bundle error using webpack for Electron application `Cannot resolve module 'electron'`

I am trying to create an Electron application with React. I use Webpack to compile the React JSX syntax, but when I try to compile with webpack command, I got this error:
ERROR in ./app.jsx
Module not found: Error: Cannot resolve module 'electron' in /Users/masterT/Downloads/gist
# ./app.jsx 6:18-37
Here is the application code.
I am doing something wrong?
A very simple solution :
const remote = window.require('electron').remote;
webpack will ignore this require
Webpack tries to resolve electron module with the installed node_modules. But the electron module is resolved in Electron itself at runtime. So, you have to exclude particular module from webpack bundling like this:
webpack.config.js:
module.exports = {
entry: './app.jsx',
output: {
path: './built',
filename: 'app.js'
},
target: 'atom',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx$/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
};
You can set target: 'electron' in your webpack config and then you don't have to exclude electron in externals.
From webpack documentation:
"electron" Compile for usage in Electron – supports require-ing Electron-specific modules.
I tried most of the above examples, but none of them seemed to work for me.
I then installed Electron using npm and then used yarn build
It worked and I got my production build.
npm i electron
Also, webpack.config.js:
const nodeExternals = require('webpack-node-externals')
module.exports = {
...
externals: [ nodeExternals(), 'react', 'electron' ],
...
}
Your package.json has 'electron-prebuilt' but you require 'electron' in your code. Have you tried require-ing 'electron-prebuild'?

Resources