Can't run wallaby.js with jest in vscode - jestjs

I have a project with jest and typescript. When I run jest, the tests run correctly.
I prepared the wallaby.config.js file:
// wallaby.config.js
export default function () {
return {
autoDetect: true,
trace: true,
files: ['src/**', '!**/*Spec.ts'],
tests: ['__tests__/**/*Spec.ts'],
debug: true,
env: {
type: 'node',
runner: 'node',
},
};
}
When I try to start I get:
Failed to initialize wallaby jest. 
Failed to read Jest configuration from '.': m is not defined 
My packages.json as type = "module"
Also, my jest.config.js looks like:
export default {
verbose: true,
testMatch: ['<rootDir>/__tests__/**/*.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
};
As I said at begin, if I type npx jest works correctly.
I want wallaby working on my vscode.

Finally I found a workaround.
First of all install jasmine and esm as dev dependency.
Now update the wallay.config.js file:
export default function configure(wallaby) {
return {
trace: true,
files: ['src/**', '!**/*Spec.ts'],
tests: ['__tests__/**/*Spec.ts'],
debug: true,
testFramework: 'jasmine', // <- added
env: {
type: 'node',
runner: 'node',
params: { //
runner: `-r esm`, // <- added
}, //
},
};
}
Now all work. I'm running test manually with jest and wallaby is using jasmine. It doesn't seem best way but works for now.

Related

Unable to run lambda in docker image

I currently have an AWS Lambda that I've been working on that I would like to build and run from a docker image. I'm using the aws-lambda-node:16 image as my base image. But I can't seem to get the docker image to properly pick up the handler from my javascript file to run the lambda.
I have tested the lambda's execution outside the docker image with lambda-local and the lambda runs fine in my local environment. It just seems that something is up with the docker container.
My Dockerfile:
FROM amazon/aws-lambda-nodejs:16
COPY dist/blacklist-ips/app.js ${LAMBDA_TASK_ROOT}
COPY package.json pnpm-lock.yaml ${LAMBDA_TASK_ROOT}/
RUN npm i -g pnpm && pnpm install --production
CMD [ "app.handle" ]
My Webpack config:
import { resolve } from 'path';
import { default as webpack } from 'webpack';
import TerserPlugin from 'terser-webpack-plugin';
const config = (env: any, argv: any): webpack.Configuration => {
return {
mode: env.production ? 'production' : 'development',
entry: {
'blacklist-ips': resolve(__dirname, 'src', 'blacklist-ips', 'blacklist-ips.ts')
},
output: {
path: resolve(__dirname, 'dist'),
filename: '[name]/app.js',
libraryTarget: 'commonjs2'
},
devtool: false,
target: 'node',
externals: [
'#aws-sdk/client-cloudwatch-logs',
'#aws-sdk/client-wafv2',
'luxon',
'tslib'
],
resolve: {
extensions: [ '.ts', '.js', '.json' ]
},
module: {
rules: [
{
test: /.ts$/,
loader: 'ts-loader'
}
]
},
optimization: {
minimize: env.production,
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
mangle: false
}
})
]
}
}
}
export default config;
My handler function is being properly exported in the webpack bundle:
const handler = async () => {
...lambda logic
};
exports.handler = handler;
I'm stumped as to why it's not working correctly with the Docker container...
Your CMD is app.handle while your function name is handler. You should change the CMD to be app.handler.

Jest Modules Do Not Import Correctly

Dealing with modules in Jest has been a nightmare.
Aside from all the other issues encountered, there is one I have yet to be able to work through.
It looks as certain imports are getting imported incorrectly.
Consider the following trivial example
import * as jp from 'jsonpath'
console.log('paths: ' + jp.paths)
when running my app code in the browser, this prints
paths: function(obj, string, count) {
assert.ok(obj instanceof Object, "obj needs to be an object");
assert.ok(string, "we need a path");
var results = this.nodes(obj, string, count)
.map(function(r) { return r.path });
return results;
}
when running the same code from a Jest test, I get:
console.log
paths: undefined
upon debugging the test and inspecting the jp object in the debugger, I see:
Needless to say this does not look correct. When running console.log(jp) from the browser, I see
It seems like Jest is screwing up the module prototype somehow.
My jest.config.js:
const esModules = ['quasar/lang', 'lodash-es'].join('|');
/* eslint-env node */
module.exports = {
globals: {
__DEV__: true,
// TODO: Remove if resolved natively https://github.com/vuejs/vue-jest/issues/175
'vue-jest': {
pug: { doctype: 'html' },
},
},
setupFilesAfterEnv: ['<rootDir>/test/jest/jest.setup.ts'],
// noStackTrace: true,
// bail: true,
// cache: false,
// verbose: true,
// watch: true,
collectCoverage: false,
coverageDirectory: '<rootDir>/test/jest/coverage',
collectCoverageFrom: [
'<rootDir>/src/**/*.vue',
'<rootDir>/src/**/*.js',
'<rootDir>/src/**/*.ts',
'<rootDir>/src/**/*.jsx',
'<rootDir>/src/**/*.tsx',
],
coveragePathIgnorePatterns: ['/node_modules/', '.d.ts$'],
coverageThreshold: {
global: {
// branches: 50,
// functions: 50,
// lines: 50,
// statements: 50
},
},
testMatch: [
// Matches tests in any subfolder of 'src' or into 'test/jest/__tests__'
// Matches all files with extension 'js', 'jsx', 'ts' and 'tsx'
'<rootDir>/test/jest/__tests__/**/*.(spec|test).+(ts|js)?(x)',
'<rootDir>/src/**/*.jest.(spec|test).+(ts|js)?(x)',
],
// Extension-less imports of components are resolved to .ts files by TS,
// grating correct type-checking in test files.
// Being 'vue' the first moduleFileExtension option, the very same imports
// will be resolved to .vue files by Jest, if both .vue and .ts files are
// in the same folder.
// This guarantee a great dev experience both for testing and type-checking.
// See https://github.com/vuejs/vue-jest/issues/188#issuecomment-620750728
moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'ts', 'tsx'],
moduleNameMapper: {
'^quasar$': 'quasar/dist/quasar.common.js',
'^~/(.*)$': '<rootDir>/$1',
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
'^layouts/(.*)$': '<rootDir>/src/layouts/$1',
'^pages/(.*)$': '<rootDir>/src/pages/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^boot/(.*)$': '<rootDir>/src/boot/$1',
'.*css$': '#quasar/quasar-app-extension-testing-unit-jest/stub.css',
},
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
'jest-transform-stub',
},
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
testEnvironment: 'jsdom'
};
Any suggestions on how to resolve this?
Thank you.

Cannot find module 'sanitize.css/page.css'

While building the gatsby project, I faced this kind of error.
yarn develop
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Cannot find module 'sanitize.css/page.css'
Require stack:
- D:\UpworkJobs\Nate\dci-gatsby-importexport\node_modules\postcss-normalize\dist\index.cjs.js
File: src\css\preview.css
failed Building development bundle - 366.725s
Here is a screenshot of the error log.
These kinds of errors occur even if I removed all CSS codes from the style files.
It seems importing CSS files is not working. If I didn't import the CSS files, the errors go away.
Here are all codes of gatsby-config.js
let systemvars = false;
if (process.env.NODE_ENV === "production") {
systemvars = true;
}
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
systemvars
});
// Gatsby automatically sets NODE_ENV to `development` or `production` when running `gatsby develop` or `gatsby build`, respectively.
// Thus make sure you have .env.development or .env.production setup (unless your CI/build env vars are already set globally)
const AliasConfig = require("./alias.config.js");
module.exports = {
siteMetadata: {
title: `DCI DigiGuide Print`,
description: `DCI DigiGuide Printable Version`,
author: `#designbycosmic`,
siteUrl: process.env.SITE_URL,
},
plugins: [
//
// * App Functionality Plugins
//
// eslint plugin
{
resolve: "gatsby-plugin-eslint",
options: {
test: /\.js$|\.jsx$/,
exclude: /(node_modules|.cache|public)/,
stages: ["develop"],
options: {
maxWarnings: undefined,
emitWarning: true,
failOnError: false,
failOnWarning: false,
},
},
},
// allows content to be placed in head
`gatsby-plugin-react-helmet`,
// adds web manifest for some pwa functionality
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-dci-digiguide-print`,
short_name: `DigiGuidePrint`,
start_url: `/`,
background_color: `#222c47`,
theme_color: `#222c47`,
display: `minimal-ui`,
icon: `./src/images/favicon.png`, // This path is relative to the root of the site.
},
},
// allow alias imports
{
resolve: "gatsby-plugin-alias-imports",
options: {
alias: AliasConfig.map,
extensions: AliasConfig.extensions,
},
},
// inline svgs instead of converting them to base64
{
resolve: "gatsby-plugin-react-svg",
options: {
rule: {
include: /svg/,
},
},
},
`gatsby-plugin-postcss`,
`gatsby-plugin-material-ui`,
// Craft CMS configuration
{
resolve: `gatsby-source-graphql`,
options: {
url: process.env.CRAFT_API_URL,
typeName: "Craft",
fieldName: "craft",
headers: {
Authorization: `bearer ${process.env.CRAFT_API_TOKEN}`,
},
},
},
// Get build date
{
resolve: `gatsby-plugin-build-date`,
options: {
formatAsDateString: false,
},
},
],
};
Help me to solve this problem.
In my case I was able to solve by adding the following configuration in package.json.
"resolutions": {
"sanitize.css": "12.0.1"
},
Finally, this problem has been solved.
Using yarn instead of using npm solved the problem.
Remove node_modules and yarn install
After that, the problem has gone away.
Thank you.

How do I use Node Typescript types with Karma-Webpack

I have Webpack configured for transpiling my TS files in Karma. I have also included Node and CoreJS types. However, when I try to run my tests I get...
ERROR in ./test/karma/test.bundle.ts
(18,30): error TS2339: Property 'context' does not exist on type 'NodeRequire'.
I tried adding webpack-env using npm install --save-dev #types/webpack-env, but that gives me even more errors.
ERROR in /.../node_modules/#types/webpack-env/index.d.ts
(183,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'RequireFunction'.
ERROR in /.../node_modules/#types/webpack-env/index.d.ts
(232,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type 'NodeModule', but here has type 'Module'.
ERROR in ./test/karma/test.bundle.ts
(18,30): error TS2339: Property 'context' does not exist on type 'NodeRequire'.
My Karma config looks like this...
var webpack = require("webpack");
module.exports = function(config) {
var webpackConfig = require("../../webpack.config");
// TODO: Can we get rid on this?
// We need to remove entry points and plugins
webpackConfig.plugins = [
// IMPORTANT!!!! Without this source maps fail to show up.
new webpack.SourceMapDevToolPlugin({
filename: null, // if no value is provided the sourcemap is inlined
test: /\.(ts|js)($|\?)/i // process .js and .ts files only
})
];
//This is used to remap can access (Based on https://github.com/sshev/karma-remap-coverage)
webpackConfig.ts = {
compilerOptions: {
inlineSourceMap: true,
sourceMap: false
}
};
webpackConfig.module.postLoaders = [
{
test: /^((?!\.spec\.ts).)*.ts$/,
exclude: /(node_modules|bower_components)/,
loader: 'istanbul-instrumenter'
}
];
webpackConfig.entry = {};
var configuration = {
autoWatch: true,
basePath: "",
browsers: ["Chrome"],
colors: true,
concurrency: Infinity,
coverageReporter: {
type: 'in-memory'
},
exclude: [
"node_modules"
],
files: [
{ pattern: "./test.bundle.ts", watched: true },
],
frameworks: ["jasmine"],
htmlReporter: {
outputFile: "../../reports/units.html"
},
logLevel: config.LOG_INFO,
port: 9876,
preprocessors: {
"./test.bundle.ts": ["webpack", "sourcemap" ],
},
remapCoverageReporter: {
"text-summary": null,
html: "./reports/coverage/html"
},
reporters: ["progress", "coverage", "remap-coverage", "html"],
singleRun: false,
webpack: webpackConfig,
webpackMiddleware: { stats: "errors-only"}
};
config.set(configuration);
};
Versions
webpack 1.14.0, node v6.9.2, Typescript 2.1.4

What's the proper way to set NODE_ENV in Karma for running webpack?

I'm building my project with Webpack and using Karma for running tests.
I want to configure Karma to set process.env.NODE_ENV to "test" for Webpack to perform conditional build of the project for testing environment with URLs mapped to localhost, not production domain name.
For that purpose I make use of Webpack's env-replace-loader, which reads its configuration file environments.json and sets variables, such as API_URL, depending on the values of process.env.NODE_ENV. In production build I use Gulp to set process.env.NODE_ENV and start webpack. It works.
I want to set process.env.NODE_ENV = 'test' in testing build, initiated by running karma start karma.conf.js. Currently I just say process.env.NODE_ENV = "test" in karma.conf.js.
Is there a better way to do that?
Besides, I tried to use DefinePlugin of webpack in webpack.config.js to set this variable like this:
const webpackConfig = {
...
plugins: [
new webpack.DefinePlugin({
process.env: {'NODE_ENV': 'test'}
}),
...
],
...
}
and it won't work: webpack env-replace-loader curses that Module build failed: TypeError: Cannot read property 'URL' of undefined - I suppose, it can not access the node reports that it doesn't see
In your webpack config try this JSON.stringify('name') instead. Try something like this:
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
APP_ENV: JSON.stringify('browser')
},
})
],
That works with the webpack running a example or something like that. For example, I'm using that to require CSS when running an example but it get ignored when compiling for production.
I got the same problem with Karma config but I fix that adding the plugin into the webpack part of the Karma config file. It's my file for example:
const webpack = require('webpack');
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
files: [
'tests.webpack.js',
{
pattern: 'src/**/__tests__/*.js',
included: false,
served: false,
watched: true
}
],
frameworks: ['jasmine'],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap', 'coverage'],
},
reporters: ['progress', 'notification'],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('test')
}
})
],
watch: true
},
webpackServer: {
noInfo: true,
}
});
};
I hope that's helpfull for you too!

Resources