How to get test name in Jest afterEach() hook - jestjs

I'm using Jest and Typescript to test api. Currently I want to map the correlation Id to each test name. I have tried to print the test name in afterEAch() hook but it didn't work. It shows error syntax "Property 'getState' does not exist on type 'Expect'". Could someone help me out?
Please note I'm using Jest v27 and jest-circus as test runner
afterEach(() => {
console.log(`Correlation ID: ${process.env.correlationId}`)
console.log(expect.getState().currentTestName)
})
Thanks

Related

Jest ToMatchSnapshot fails on unit test after aws-cdk-lib update from 2.27.0 to 2.28.0

I am working on some code that is using jest ToMatchSnapshot to compare an aws stack created from the current unit test, with one that was created prior to any code changes. The code that the unit test is running looks like this.
test('adds lambda function widgets', () => {
const stack = testStack()
new lambda.Function(stack, 'Function', {
-- some code
})
const template = Template.fromStack(stack)
expect(template.toJSON()).toMatchSnapshot()
})
when I update the reference for aws-cdk-lib from 2.27 to 2.28 the unit test fails. The error is a mismatch of the S3Key property of an S3Bucket. I looked in the AWS account and I can find the S3Bucket name that is in the template, but not the S3Key, neither the old one nor the new one. I need to know whether this is a substantial change that somehow needs to be fixed so the snapshot pre-update matches the post-update, or if this is something trivial and I can just update the snapshot.
I updated the version of aws-cdk-lib
I am expecting no errors in the unit test
I am getting and error of a mismatched S3Key property

Cypress with BDD Cucumber how to create my own data type

I am using cypress with cucumber-js and i need to define my own data type. I did exactly same things like is described in https://github.com/TheBrainFamily/cypress-cucumber-preprocessor#custom-parameter-type-resolves.
That means:
cypress > support > step_definitions > customParameterTypes.js
I wrote:
const blogType = ["sport", "gaming"]
defineParameterType({
name: "blogType",
regexp: new RegExp(blogType.join("|"))
})
and in my BDD .feature file i have:
Given I have empty blog
And Blog has default structure for sport
and in my cypress file:
Given(' Blog has default structure for {blogType}', blogType => {...})
When i start my test i get:
The following error originated from your test code, not from Cypress.
> Undefined parameter type {blogType}
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
Cypress could not associate this error to any specific test.
For some reasons, I've had problems using defineParameterType() in the past, and am now using regexp in all my BDD projects.
In your .js file:
Given(/^Blog has default structure for (sport|gaming)$/, blogType => {...});
Using the above, you won't need customParameterTypes.js and your .feature file stays the same.

JEST Change pre-formatted output from test case

I have an application that runs a Jest test suite from the command line, then takes the JSON output, parses it and then fills table in a database as per the output file. The application runs shell command:
npm run all
and in the package.json file the all script looks like this:
"scripts": {
"all": "../node_modules/.bin/jest --json --outputFile=testResults.json",`
......
}
So I get the testResults.json file and I am able to parse it - so far so good.
But during the test case run I would like to add some extra data to the output. Something like details - where the problems is, how to fix it, some troubleshooting information etc. For example to put one more field in :
require('testResults.json').testResults[x].assertionResults[y].details
You see, the detail property is not part of the json output file format. But can I create it from within the test case (pseudo example):
test('Industry code should match ind_full_code', async () => {
result = await stageDb.query(QUERY);
// And here I want to add this custom information to some global property available?
reporter.thisTestCase.assertionResults.details = "Here is what you should do to fix this ...." // <- Ideally this is how easy I imagine it to be.
expect(result.results).toEqual([]);
}, 2 * 100 * 1000)
I just want to give a little bit more information to the QA or whomever on test failure.
In other words I need the option to change the output from within the test case.
I've been looking into custom reporters, but their listeners are passed the same information as to the json reported.
I've found a need for a similar feature in Jest. The ability to add documentation to the test is rarely supported by test frameworks.
However I found a way to do this with the soon to be default runner: Jest Circus. I then made my own Jest Circus environment. A custom Jest Circus environment provides more test events/lifecycles and access to the actual test code that is being ran.
// Example of a custom Jest Circus environment
export default class MyCustomNodeEnvironment extends NodeEnvironment {
handleTestEvent(event: Circus.Event, state: Circus.State) {
if(event.name === 'test_fn_start') {
console.log(event.test.toString())
// will log the actual test code.
}
}
}
// jest.config.js
{
"testEnvironment": "<rootDir>/my-custom-environment.js",
"testRunner": "jest-circus/runner"
}
I then used regex patterns to find comments in the test functions and add them to the Allure report (Allure report demo).
If you'd like to create your own Jest environment and implement this yourself I've made a template repo or if you prefer a gist of a basic Jest Circus environment.
If you like how Allure reports look you should checkout my open source project jest-circus-allure-environment.

jest method done() is not defined

I started using jest and I now need to test callbacks.
To know when a callback was called, the done() is supposed to be used accourding to the documentation: https://jestjs.io/docs/en/asynchronous.html
However the done() is not recognized beeing undefined and is consequently throwing this Error:
Test suite failed to run
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
pathToErrorFile:line - error TS2304: Cannot find name 'done'.
63 done();
~~~~
//code to reproduce:
test('test', ()=>{
fkt(param, ()=>{
done();
});
});
I have setup jest with node and angular and in both projects this function does not exist.
So what I want to know is, where this function is even coming from and how I can troubleshoot it.
Note that everything else (test, describe, etc. ) is working fine done() as its exception.
done is not defined as a global var. You get it passed to the test function.
test('test', done => {
fkt(param, () => {
done();
});
});
Note that if you specify done parameter, jest will detect it and will fail the test on timeout, if the done function is not called after the test has finished.
If done() is never called, the test will fail (with timeout error), which is what you want to happen.
Then, you have to call done even if the test fails - otherwise you won't see the error.
If we want to see in the test log why it failed, we have to wrap expect in a try block and pass the error in the catch block to done. Otherwise, we end up with an opaque timeout error that doesn't show what value was received by expect(data).
See Jest - Testing Asynchronous Code

Handling process.exit(1) with Jest

I am writing my unit tests for NodeJS using Jest.
A part of my code exits using process.exit(1), so when trying to test it using Jest, the test terminates when it comes to this line with the error Command failed with exit code 1. which is the default behaviour of process.exit(1).
Can anyone please tell how to work with Jest to handle this scenario and continue with the other tests?
I think, throwing an error instead gives a more maintainable and testable code for you. Like:
if (err) {
throw new Error("Some relevant error msg")
}
If you insist on using process.exit(1), you can test for process.exitCode, which should be 1 in your case.

Resources