Custom Jest Serializer with Enzyme - jestjs

Are there any examples for how I would take a components with Enzyme's shallow render function and serialise it into a snapshot which is more readable?
I looked into the documentation for addSnapshotSerializer and tried to look into the code for enzyme-to-json without much luck.
In the end I came up with variations on,
expect.addSnapshotSerializer({
test: v => true,
print: (v, s) => Object.keys(s)
});
But that didn't get me far either.
Suspect I am barking up the wrong tree!

Have you tried https://github.com/rogeliog/jest-serializer-enzyme?
jest-serializer-enzyme
This is a serializer for Enzyme backed by enzyme-to-json, I suggest
looking at enzyme-to-json for the implementation details
Install it
npm install --save-dev jest-serializer-enzyme Add it to your jest
config
"jest": { "snapshotSerializers":
["/node_modules/jest-serializer-enzyme"] } More about Jest's
snapshotSerializer config here.

Try to use enzyme-to-json which snapshot test your Enzyme wrappers.

Related

Express +Jest. Test files are running sequentially instead of in parallel

I have an Express.JS server which uses jest and supertest as a testing framework.
It has been working excellently.
When I call my test npm script, it runs npx jest and all of my test files run in parallel.
However I ran my tests recently and they ran sequentially which takes a very long time, they have done this ever since.
I haven't changed any jest or npm configuration, nor have I changed my test files themselves.
Has anyone experienced this? Or is it possible that something in my configuration is incorrect?
jest.config
export default {
setupFilesAfterEnv: ['./__tests__/jest.setup.js'],
}
jest.setup.js
import { connectToDatabase } from '/conn'
// Override the dotenv to use different .env file
require('dotenv').config({
path: '.env.test',
})
beforeAll(() => {
connectToDatabase()
})
test('', () => {
// just a dummy test case
})
EDIT: Immediately after posting the question, I re ran the tests and they ran in parallel, without me changing anything. If anyone has any knowledge around this i'd be interested to get a second opinion
After intermittent switching between parallel and sequential for unknown reasons. I have found it work consistently by adding the --no-cache arg to the npx jest call.
See below where I found the answer
Github -> jest not always running in parallel

Jest cannot find module 'got' from node_modules

I'm getting an error from one of my (previously working) tests when I run yarn jest:
Cannot find module 'got' from 'src/rss/queries.ts'
I've added got in package.json:
"devDependencies": {
"got": "^12.0.0",
}
My jest.config.js:
module.exports = {
preset: 'ts-jest',
testMatch: ['**/*.test.ts(|x)'],
collectCoverageFrom: ['**/*.ts', '!.webpack/**/*'],
verbose: true,
}
I'm using got in ./src/rss/queries.ts:
import * as got from 'got'
I've also tried:
import { got, RequestError } from 'got'
In both cases the application works - I can see got making requests via the application logs (and vscode is indicating the correct path to the module in node_modules when I hover over the above). So it's definitely there, and working.
But jest can't find it. Why? It's not an uncommon stackoverflow question, but they all seem to relate to importing custom local modules via relative paths, etc. I'm just trying to use one out of node_modules...
Version 12 of got doesn't work with jest. Best to use version 11 for now. See the details in the release notes at: https://github.com/sindresorhus/got/releases/tag/v12.0.0
Wasn't able to find a reason for, or solution to, this. Ended up swapping got for axios, which is a shame as I liked many got features.

Console.log statements output nothing at all in Jest

console.log statements output nothing at all in Jest. This was working for me yesterday, and all of sudden, it's not working today. I have made zero changes to my config and haven't installed any updates.
I'm not using the --forceExit option. Still seeing this issue.
Jest suppresses the console log message by default. In order to show the console log message, set silent option to false at the command line
set --silent=false in the command line:
npm run test -- --silent=false
You can run both options together like this --watch --verbose false if you want to also be watching the files and see the output.
for one time runs just do --verbose false
As per comment on https://github.com/facebook/jest/issues/2441,
Try setting verbose: false (or removing it) in the jest options in package.json.
This is a pretty old question and still there's no accepted answer. However, none of the suggested solutions worked for me (settings like --silent --verbose etc.). The main problem is that Jest changes the global console object. So, the easiest solution is to not use the global console object.
Instead import dedicated log functions from the console module and work with those:
import { error } from "console";
error("This is an error");
As easy as that.
Try using console.debug() instead.
Run console.debug('Message here', yourValueHere) inside test function and it should show in the console output when running test script. You can verify if it works using Ctrl+F and find Message here in the standard output.
This does the trick of showing output in the console, while it is not an answer quite on how to use console.log I understand.
I am running #testing-library/jest-dom and jest-junit 12.0.0 as devDependencies.
jest-junit has a minimal configuration of
"jest-junit": {
"usePathForSuiteName": "true"
},
in package.json. This is mainly to configure coverage reporting.
jest is configured like this:
"jest": {
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[jt]s?(x)",
"!**/utilities.ts",
],
Check for your command line flags in package.json to see that you don't have --silent in there.
in addition to --verbose option which can cause this as mentioned, be aware that the --watch may also cause this bug.
One of the potential reason that logging is not printing is due to console.log has been mocked. Something as below
// jest-setup.js
global.console = {
// eslint-disable-next-line no-undef
log: jest.fn(), // console.log are ignored in tests
// log: console.log,
// Keep native behaviour for other methods, use those to print out things in your own tests, not `console.log`
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug,
};
// package.json
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect",
"<rootDir>/src/config/jest-setup.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.test.{ts,tsx}"
]
},
This is commonly used if you wish to disable console.log in jest
Also be sure that your jest config does not have silent: true. In my case, I didn't realize that someone else had added that to our config.
I don't see it in the list of config options, but the command line flag is documented here.
If using Webstorm with Jest configuration, click on the file name instead of the test name.
Having tried a few of the config options in the previous replies, using console.debug() instead of console.log() worked.
In my case, the issue was caused by [only] flag in:
it.only() or test.only('some text',()=>{})
According to the v27 docs silent is what you want here. verbose false (the default) prevents Jest from outputting the result of every test in a hierarchy while silent true (the default) will:
Prevent tests from printing messages through the console.
Use npx jest --silent false if you want to run Jest with that option from the CLI. Tested this just now with console.log and it works as expected.
Tried the advice given regarding jest config settings to no avail. Instead, in my case, the issue seemed related to not awaiting asynchronous code:
test("test", async () => {
console.log("Does output")
new Promise(resolve => {
// some expectation depending on async code
setTimeout(() => resolve(console.log("Does not output")) , 1)
})
})
Rather, awaiting the promise does output the async log:
test("test", async () => {
console.log("Does output")
await new Promise(resolve => {
// some expectation depending on async code
setTimeout(() => resolve(console.log("Does output")) , 1)
})
})
Possibly related background:
https://github.com/facebook/jest/issues/2441
Try using console.info() which is an alias for console.log(). I tried almost all the above answers but still console.log() didn't worked for me by any means. So, used console.info() which did the work.
This is what worked for me: jest --verbose true
In my case the problem was that the logs where made when the module is required, so before the start of an actual test case. Change from a top-level import to using require inside the test case fixed the problem.
In my case the problem was importing the functions from the compiled version (present in dist folder) instead of the src folder. And therefore it was using the old version. So rebuilding the project and/or importing from src fixed my issue.
On MacOS with jest version 26.6.3 I had to append --silent="false"
renaming my file to index.test.js from index.spec.js did the trick for me.

Babel: "The keyword 'await' is reserved (53:24)"

We're using async/await for our Meteor project. This syntax is everywhere in our resolvers.js. Everything has been working fine until we've upgraded to Node 6.7. Now it shows this error every time we try to build it:
"The keyword 'await' is reserved (53:24)"
Does anyone know how to solve this?
Here is the content of my .babelrc file:
{
"presets": ["es2015", "stage-2", "react"],
"plugins": ["react-require", "babel-root-slash-import"]
}
Just in case anyone else searches for this same issue, in my case it was user error, me. I forgot to put the async keyword before the function name.
Okay, I found out a solution to my own problem. I just excluded the .babelrc when doing a Meteor build since Meteor already has a package that supports ES6 syntax. I didn't totally remove the .babelrc because I will be needing it on tests and when running the Storybook which does not trigger a Meteor build.
Await alone is invalid syntax. await needs to be called inside an async function like:
var aFunction = async function() {
let aResponse = await get('aValue');
}

Declare test dependency using Npm.depends

I would like to know how to declare a dependency on an Npm module in Meteor only in test.
While testing a package, I can easily declare a Npm dependency in package.js like this:
Npm.depends({
...
'sinon': '1.15.3'
...
});
But I am only using sinon in test, and I want to make it explicit.
I tried the following with no success.
Package.onTest(function(api) {
// # 1
// can't do this because it is not a meteor module
api.use('sinon');
// # 2
// can't because I have other production Npm dependencies
// and Meteor only allows one `Npm.depends` call per `package.js`.
// Also, not sure if nesting Npm.depends() is allowed at all.
Npm.depends({
'sinon': '1.15.3'
});
});
Any suggestions?
The only way to do this is to wrap sinon into a package and api.use it. You can do the following:
$ meteor create --package sinon
Replace the contents of packages/sinon with the following:
package.js
Package.describe({
summary: 'Standalone test spies, stubs and mocks for JavaScript.'
});
Package.onUse(function(api) {
api.versionsFrom('1.0.4');
api.export('sinon', 'server');
api.addFiles('sinon.js');
api.addFiles('post.js');
});
post.js
sinon = this.sinon;
sinon.js
Download the latest version from here.
Finally in the package you are testing, you can add api.use('sinon'); in your Package.onTest.
As an alternative to making your own package, you can just use one of the community versions available here.

Resources