How to configure Babel when unit testing a Sanity Studio project - unit-testing

I'm using sanity.io as a headless CMS and am trying to unit test some of my code. Sanity internally uses babel to pre-compile the source code.
For my unit tests I am using mocha and am invoking it with the following script (in package.json)
"scripts": {
"test:unit": "find ./test/unit -name '*.spec.js' | NODE_ENV=test xargs mocha --require babel-core/register --require ./test/unit/testHelper.js"
},
If I add my own .babelrc file to the root of my project then the tests work, but running sanity start fails.
The .babelrc file I am using contains
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"transform-object-rest-spread"
]
}
If I don't add my own .babelrc file then sanity start works but the tests fail as babel is not being configured.
How can I tell babel to only use a specific config when I am running tests.

Related

How to add subresources integrity with Angular appShell build

I built an application with Angular CLI 9.
I patched the package.json file with :
{
"scripts": {
"build:prod": "ng build --prod --subresource-integrity",
"prebuild:prod": "TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\"}' ts-node ./sitemap_generator.ts"
}
}
So, when I called npm run build:prod, my 2 commands are executed and output files generated by compiler contains SRI.
Now, I added the appShell :
npm run ng generate appShell -- --client-project my-project
To run the build with the appShell, I have to use the command :
npm run ng run my-project:app-shell:production
MAIN QUESTION
But this command calls my-project:build:production configuration of angular.json file, and this does not accept the --subresource-integrity argument :/
How to patch this to have appShell production build with SRI ?
SECONDARY QUESTION for the braves
This appShell build create a server/ folder in dist/. It just contains a main.js file. I suppose it's internally used with Node to build the appShell ; can someone confirm that ?
And so, can I use Unversal too with this architecture to do some SSR for search engines ?
Thanks !
Ok, I found a way by editing angular.json :
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "my-project",
"projects": {
"oce-training": {
"architect": {
"build": {
"configurations": {
"production": {
"subresourceIntegrity": true,
}
}
}
}
}
}
}
So, we cannot override on package.json or by CLI command, but it's sufficient for my case.
Now I have in package.json:
{
"scripts": {
"build:prod": "ng run oce-training:app-shell:production",
"prebuild:prod": "TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\"}' ts-node ./sitemap_generator.ts"
},
}
My question about SSR is maintained, but it could be another Stackoverflow post ;)

What happens if more than one Jest configuration is used simultaneously?

Jest's configuration states:
Jest's configuration can be defined in the package.json file of your
project, or through a jest.config.js file or through the --config <path/to/js|json> option.
What happens if a configuration setting is defined in two or more places? Are distinct configuration settings merged together or can they be silently ignored? If merging or ignoring, do they have a well defined or ad hoc precedence?
I inherited multiple projects with both a "jest" object in package.json and "jest.config.js" file, each with their specific configuration.
By playing (superficially) with the coverage threshold (which was < 97%), I came to the conclusion that jest.config.js is used, and the jest object in package.json is ignored. There doesn't seem to be any merging going on.
My tests:
#1: Which has priority ?
package.json: coverage 98%
jest.config.js: coverage 99%
=> "coverage threshold for statements (99%) not met"
Answer: jest.config.js
#2: Are they merged ?
package.json: coverage 98%
jest.config.js: (missing coverage key)
=> no coverage warnings
Answer: No
To answer a subset of the full problem (which may be too complicated for a meaningful set of tests as it's a lot of knobs to twiddle), if a jest command line --config (or -c) is provided, then package.json jest settings are ignored.
More specifically to come to this conclusion, firstly I tried jest -c jest/config.js with setupFilesAfterEnv in my jest/config.js:
module.exports = {
rootDir: '../',
setupFilesAfterEnv: ['./jest/global-setup.js'],
}
File jest/global-setup.js contains:
const Enzyme = require('enzyme')
const Adapter = require('enzyme-adapter-react-16')
require('jest-enzyme/lib/index.js')
Enzyme.configure({ adapter: new Adapter() })
Which here has the desired effect of running the enzyme setup. Commenting it out in the jest/config.js file and putting the equivalent into package.json is skipped/ignored:
"jest": {
"setupFilesAfterEnv": ["./jest/global-setup.js"],
},
Secondly I tried jest -c jest/config.js with a jest fileTransformer.js file and the following in my jest/config.js:
transform: {
'^.+\\.js$': 'babel-jest',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/jest/file-transformer.js',
},
Then the equivalent jest.transform setting of package.json is skipped/ignored:
"jest": {
"transform": {
"^.+\\.js$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest/file-transformer.js"
}
},
Thirdly, changing my npm scripts test command from jest -c jest/config.js to jest and my package.json to include the following causes the package.json settings to work as expected:
"jest": {
"setupFilesAfterEnv": ["./jest/global-setup.js"],
"transform": {
"^.+\\.js$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/jest/file-transformer.js"
}
},
Tested with jest v24.9.0

Can prettier plugin get integrated into the web IDE when saving js files?

I would like to configure Prettier within the WebIDE, so far without success.
In my package.json file, I have the following settings:
"scripts": {
"format": "prettier --write \"webapp/**/*.{js,css,json}\""
},
"devDependencies": {
"prettier": "^1.14.3",
"eslint": "^5.7.0",
"eslint-plugin-prettier": "^3.0.0",
"eslint-config-prettier": "^3.1.0" //Here I get ESLint error cannot find module
}
Then, in my .eslintrc.json file:
"extends": ["eslint:recommended", "prettier"]
This is not really working, my goal is to format according to Prettier when I save a file (similar to the "beautify code" option in the web IDE code editor settings, which is now switched off).
I tried cleaning the npm folder and building again, but nothing happens.

Vue-test-utils | Jest: How to handle dependencies?

THE SITUATION:
I am implementing unit-testing in my Vue app, using vue-test-utils with Jest configuration.
When I am testing simple components everything is fine. But when I am testing components that import other dependencies, the test fails.
CONFIGURATION:
Vue version: 2.5.17
#vue/test-utils: 1.0.0-beta.20
cli-plugin-unit-jest: 3.0.3
babel-jest: 23.0.1
THE ERROR MESSAGE:
The exact error message depends on which dependency I am importing.
For example with epic-spinners the error is:
SyntaxError: Unexpected token import
With vue-radial-progress the error is:
SyntaxError: Unexpected token <
HOW TO REPRODUCE:
Make a fresh install of vue (with Jest as unit testing suite)
Run the example test, it should pass
Install a dependency (for example: npm install --save epic-spinners)
Import the dependency inside the HelloWorld component
Run the test again (without changing anything)
If I do these steps, the test fails with the above error message.
THE QUESTION:
How can I handle dependencies import in vue-test-utils / Jest ?
The problem was that some modules may not be compiled correctly.
The solution is to use the transformIgnorePatterns property of the Jest settings. That is, from the docs:
An array of regexp pattern strings that are matched against all source
file paths before transformation. If the test path matches any of the
patterns, it will not be transformed.
In my case, this is how I have solved the issue:
transformIgnorePatterns: [
"node_modules/(?!epic-spinners|vue-radial-progress)"
],
EDIT:
This is my jest.config.js
module.exports = {
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue'
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: [
"node_modules/(?!epic-spinners|vue-radial-progress)"
// "node_modules/(?!epic-spinners)",
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost/'
}
In addition to #FrancescoMussi's answer, after editing my jest.config.js, in case you get the error: jest-transform-stub not found, just install it. in my case I didn't had installed jest-transform-stub and jest-serializer-vue. after installing those my tests started working.
npm install --save-dev jest-serializer-vue
https://www.npmjs.com/package/jest-serializer-vue
and
npm install --save-dev jest-transform-stub
https://www.npmjs.com/package/jest-transform-stub
In addition to #FrancescoMussi's solution, if it is still not working for you, make sure your Babel config is in the correct place as per the Jest docs
I had moved my Babel config to package.json which Babel wasn't detecting due to Vue CLI installing Babel 7. Moving Babel config back to babel.config.js resolved the issue for me.

How to make mocha watch, compile and test coffeescript with dependencies on save

I'm working on a project that uses coffeescript for development and testing. I run the tests in node with mocha's --watch flag on so I can have the tests run automatically when I make changes.
While this works to some extent, only the ./test/test.*.coffee files are recompiled when something is saved. This is my directory structure:
/src/coffee
-- # Dev files go here
/test/
-- # Test files go here
The mocha watcher responds to file changes inside the /src and /test directories, but as long as only the files in the /test directory are recompiled continuous testing is kind of borked. If I quit and restart the watcher process the source files are also recompiled. How can I make mocha have the coffee compiler run over the development files listed as dependencies inside the test files on each run?
Here is my answer using grunt.js
You will have to install grunt and few additionnal packges.
npm install grunt grunt-contrib-coffee grunt-simple-mocha grunt-contrib-watch
And write this grunt.js file:
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
coffee:{
dev:{
files:{
'src/*.js':'src/coffee/*.coffee',
}
},
test:{
files:{
'test/test.*.js':'test/test.*.coffee'
}
}
},
simplemocha:{
dev:{
src:"test/test.js",
options:{
reporter: 'spec',
slow: 200,
timeout: 1000
}
}
},
watch:{
all:{
files:['src/coffee/*', 'test/*.coffee'],
tasks:['buildDev', 'buildTest', 'test']
}
}
});
grunt.registerTask('test', 'simplemocha:dev');
grunt.registerTask('buildDev', 'coffee:dev');
grunt.registerTask('buildTest', 'coffee:test');
grunt.registerTask('watch', ['buildDev', 'buildTest', 'test', 'watch:all']);
};
Note: I didn't have some detials on how you build / run your tests so you certainly have to addapt ;)
Then run the grunt watch task :
$>grunt watch
Using a Cakefile with flour:
flour = require 'flour'
cp = require 'child_process'
task 'build', ->
bundle 'src/coffee/*.coffee', 'lib/project.js'
task 'watch', ->
invoke 'build'
watch 'src/coffee/', -> invoke 'build'
task 'test', ->
invoke 'watch'
cp.spawn 'mocha --watch', [], {stdio: 'inherit'}
Mocha already watches the test/ folder, so you only need to watch src/.