Test ES6 modules with Jest [duplicate] - unit-testing

This question already has answers here:
Does Jest support ES6 import/export?
(10 answers)
Closed 11 months ago.
How to test ES6 modules with Jest.
Example:
sum.js
const sum = function (a, b) {
return a + b;
}
export default sum;
sum.test.js
import sum from './sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

The only requirement is to config your test environment to Babel, and add the es2015 transform plugin:
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the es2015 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
And that's it. Jest will enable compilation from ES modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.

The solutions above didn't work for me. I was able to solve with this:
yarn add --dev babel-jest #babel/core #babel/preset-env #babel/preset-typescript
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'#babel/preset-typescript'
],
};
where I'm using typescript.
Reference.

Related

guardReactiveProps warn in build with vite

I want to build my nuxt project with vite and rollup
and after I entered npm run build the build finishes successfully but it prints this warning:
"guardReactiveProps" is imported from external module "vue" but never used in "src/components/MyComponent.vue, and rest of my components!
please help me to fix this warning
here are my configs
package.json
"rollup": "^3.5.1",
"rollup-plugin-visualizer": "^5.8.3",
"vite": "^4.0.0",
vite.config.ts
import { resolve } from 'path'
import { defineConfig } from 'vite'
export default defineConfig({
build: {
rollupOptions: {
external: [
'bootstrap',
'bootstrap/js/dist/alert',
'bootstrap/js/dist/collapse',
'bootstrap/js/dist/modal',
'bootstrap/js/dist/offcanvas',
'bootstrap/js/dist/popover',
'bootstrap/js/dist/carousel',
'bootstrap/js/dist/dropdown',
'bootstrap/js/dist/tooltip',
'vue',
'#popperjs/core',
'#vueuse/core'
],
output: {
exports: 'named',
assetFileNames: `routaa-ui-kit.[ext]`, //without this, it generates build/styles.css
globals: {
vue: 'Vue',
bootstrap: 'Bootstrap',
'#vueuse/core': 'vueuse',
'bootstrap/js/dist/collapse': 'Collapse',
'bootstrap/js/dist/alert': 'Alert',
'bootstrap/js/dist/carousel': 'Carousel',
'bootstrap/js/dist/dropdown': 'Dropdown',
'bootstrap/js/dist/modal': 'Modal',
'bootstrap/js/dist/offcanvas': 'Offcanvas',
'bootstrap/js/dist/popover': 'Popover',
'bootstrap/js/dist/tooltip': 'Tooltip'
}
}
}
},
})
Thanks.

Emit attempted before Angular Webpack plugin initialization after webpack5 build

I'm using Angular 14 ang webpack version: ^5.58.1.
Below is the config:
webpack.congif.js
const webpackPlugin = require('#ngtools/webpack').AngularWebpackPlugin;
module.exports = {
mode: 'development',
devtool: "source-map",
entry: {
main: "./js/main.js",
mainDrawer: "./js/divdrawer/main.ts",
polyfills: "./js/divdrawer/polyfills.ts",
entry: "./js/entry.js",
thirdpartylibs: "./js/thirdpartylibs.js"
},
output: {
path: path.join(__dirname, "build/"),
filename: "[name]bundle.js"
},
module: {
rules: [
{
parser: {
system: true,
}
}
test : /\.(tsx|ts)$/,
use: [
{
loader: '#ngtools/webpack',
options: {
configFile: path.resolve('./js/tsconfig.json')
},
},
]
},
},
plugins: [
new webpackPlugin({
tsconfig: './js/tsconfig.json',
}),
new webpack.ContextReplacementPlugin(
/\#angular(\\|\/)core(\\|\/)esm5/,
path.resolve(__dirname, "./js/divdrawer")
)
]
}
While generating the build I'm getting below error:
ERROR in ./js/divdrawer/filterMappingRemover.ts
Module build failed (from ./node_modules/#ngtools/webpack/src/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.
at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18
# ./js/entry.js 10:30-97
ERROR in ./js/divdrawer/main.ts
Module build failed (from ./node_modules/#ngtools/webpack/src/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.
at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18
at processTicksAndRejections (internal/process/task_queues.js:95:5)
ERROR in ./js/divdrawer/polyfills.ts
Module build failed (from ./node_modules/#ngtools/webpack/src/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.
at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18
ERROR in ./js/divdrawer/renderer.ts
Module build failed (from ./node_modules/#ngtools/webpack/src/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.
at D:\MyProject\node_modules\#ngtools\webpack\src\ivy\loader.js:81:18
# ./js/entry.js 9:18-61
All the entries are throwing the errors with above message. As mentioned in webpack config we have multiple entries.
This is detected when I upgraded our project to angular 14.(Angular upgrade Steps: v10 --> v11--> v12--> v13/v14)
How to configure AngularWebpackPlugin correctly? Is there any alternative way?
For me this solution worked:
go to package.json and change your typescript version, If you want to upgrade your angular project to
Angular 15 (npm install typescript#"~4.8.0" --save-dev)
"devDependencies": {
...
"typescript": "~4.8.0"
}
Angular 14 (npm install typescript#"~4.7.0" --save-dev)
"devDependencies": {
...
"typescript": "~4.7.0"
}
Credit to F.R
yes downgrading typescript version to 4.8.2 resolve the issue.
For me, upgrading node version 16.xx to 18.xx (LTS) fixed the issue.

Using a (Zustand) function mock with Jest results in "TypeError: create is not a function"

I'm following the Zustand wiki to implement testing, but the provided solution is not working for a basic test for app rendering. My project is built on top of the Electron React Boilerplate boilerplate project.
Here's the full error. Jest is using node with experimental-vm-modules because I followed the the Jest docs to support ESM modules.
$ cross-env NODE_OPTIONS=--experimental-vm-modules jest
(node:85003) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
jest-haste-map: Haste module naming collision: myproject
The following files share their name; please adjust your hasteImpl:
* <rootDir>/package.json
* <rootDir>/src/package.json
FAIL src/__tests__/App.test.tsx
● Test suite failed to run
TypeError: create is not a function
12 | }
13 |
> 14 | const useNotifs = create<NotifsState>(
| ^
15 | // devtools(
16 | (set) => ({
17 | notifStore: notifsDefault.notifStore,
at src/state/notifs.ts:14:19
at TestScheduler.scheduleTests (node_modules/#jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/#jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/#jest/core/build/cli/index.js:408:7)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 11.882 s
Ran all test suites.
error Command failed with exit code 1.
At the top of the notifs.ts file, Zustand is imported normally with import create from 'zustand'.
Jest config in package.json:
...
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/mocks/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy",
"zustand": "<rootDir>/src/__mocks__/zustand.js",
},
"transformIgnorePatterns": [
"node_modules/(?!(zustand)/)",
"<rootDir>/src/node_modules/"
],
"moduleDirectories": [
"node_modules",
"src/node_modules"
],
"moduleFileExtensions": [
"js",
"jsx",
"ts",
"tsx",
"json"
],
"moduleDirectories": [
"node_modules",
"src/node_modules"
],
"extensionsToTreatAsEsm": [
".ts",
".tsx"
],
...
I have left the ./src/__mocks__/zustand.js file exactly the same as from the Zustand wiki Testing page. I receive the same error whether or not I have zustand in the transformIgnorePatterns.
My Babel configuration includes [require('#babel/plugin-proposal-class-properties'), { loose: true }], in the plugins section, and output.library.type is 'commonjs2'
My tsconfig.json has compilerOptions.module set to "CommonJS", and the project's package.json "type" field is set to "commonjs".
Dependency versions:
"#babel/core": "^7.12.9",
"#babel/preset-env": "^7.12.7",
"#babel/preset-react": "^7.12.7",
"#babel/preset-typescript": "^7.12.7",
"#babel/register": "^7.12.1",
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#testing-library/jest-dom": "^5.11.6",
"#testing-library/react": "^11.2.2",
"babel-jest": "^27.0.6",
"babel-loader": "^8.2.2",
"jest": "^27.0.6",
"regenerator-runtime": "^0.13.9",
"source-map-support": "^0.5.19",
"typescript": "^4.0.5",
"webpack": "^5.5.1",
"zustand": "^3.5.5"
I don't know what else could be relevant, just let me know if anything else is needed. Any and all help appreciated, thanks for your time.
To do this you should use the actual store of your app
const initialStoreState = useStore.getState()
beforeEach(() => {
useStore.setState(initialStoreState, true)
})
useStore.setState({ me: memberMockData, isAdmin: true })
The documentation seems off. So don't follow it.
use jest 28.0.0-alpha.0 will simply resolve the issue.
I think the problem is zustand uses '.mjs' as the entry point.

How to run Rails System tests in Heroku CI

How do I configure Heroku CI to run System tests?
This is my app.json, where I included what I thought would be the necessary buildpacks:
{
"environments": {
"test": {
"scripts": {
"test-setup": "bin/rails assets:precompile",
"test": "bin/rails test:system"
},
"addons":[
"heroku-postgresql:in-dyno"
],
"buildpacks": [
{ "url": "https://github.com/heroku/heroku-buildpack-google-chrome" },
{ "url": "heroku/nodejs" },
{ "url": "heroku/ruby"}
]
}
}
}
But when I deploy, I get the following error:
-----> Running test command `bin/rails test:system`...
rails aborted!
Webdrivers::BrowserNotFound: Failed to find Chrome binary.
I suspect I am missing something very basic....
I running Rails 6.0.1 and Ruby 2.6.3.
Did you setup your webdriver correctly to find the correct binary as mentioned on the official UAT wiki page of heroku?
Add gem 'webdrivers' to your Gemfile.
Add the following code snippet to your test_helper.rb (as stated on heroku buildback wiki and on webdrivers wiki):
require 'webdrivers' # Make sure webdrivers are loaded.
chrome_bin = ENV['GOOGLE_CHROME_SHIM'] if ENV['GOOGLE_CHROME_SHIM'].present?
chrome_capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: {
# You may want to use a different args
args: %w[headless disable-gpu window-size=1400x1400],
binary: chrome_bin
}
)
Capybara.register_driver :heroku_chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, desired_capabilities: chrome_capabilities)
end
Afterwards tell your system test to use your custom chrome driver by adding it to your application_system_test_case.rb.
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :heroku_chrome
end

Verbose output in jest js

is any option for verbore output for testing by jest?
I can see which modules are mocked.
I tried
jasmine.VERBOSE = true;
but not working.
Thanks for answer.
To get verbose mode in Jest, you can run Jest with the --verbose tag.
In your packages.json, you can write:
"scripts": {
"test": "jest --verbose"
},
Then you can run npm test
Alternatively, if you are using gulp-jest, to get Jest in verbose mode, find the index.js file of the gulp-jest folder in node_modules and add a verbose: true to the jest.runCLI block.
jest.runCLI({
config: options,
verbose: true
}
simple add in package.json
{
...
...
"jest": {
"verbose": true
},
...
...
}
Create jest.config.js file in root directory and add this to the module export
module.exports = {
// some code here..
verbose: true,
// some code here...
}