I am running Jest and am trying to log the start and end timestamp for each of my tests. I am trying to stick my timestamp logging inside the beforeEach()
and afterEach()
blocks. How would I log the name of my Jest test within the beforeEach()
and afterEach()
block?
Also, is there a more global way of logging test name and timestamp before and after all the tests without using beforeEach()
and afterEach()
?
afterEach(fn) Runs a function after each one of the tests in this file completes. If the function returns a promise, Jest waits for that promise to resolve before continuing. This is often useful if you want to clean up some temporary state that is created by each test.
If you're certain that the tests don't make any changes to those conditions, you can use beforeAll (which will run once). If the tests do make changes to those conditions, then you would need to use beforeEach , which will run before every test, so it can reset the conditions for the next one.
afterEach() is a hook or global method provided by Mocha that will execute after each test case in a block. It is usually used to clean-up after your test cases.
You can read this article https://jestjs.io/docs/en/setup-teardown.html on Jest document. Note, that a scoped beforeAll in a nested describe will run before a parent beforeEach . So if you depend on something in a parent beforeEach in your scoped beforeAll , it will not have run yet.
You can access the name of the current test in jest like this:
expect.getState().currentTestName
This method also works inside beforeEach
/ afterEach
The only downside is that it will also contain the name of your current describe section. (which may be fine depending on what you are trying to do.
Also it does not give you the timing information that you asked for.
The information on currently running test is unavailable in beforeEach
. Similarly to Jasmine, suite object is available in Jest as this
context in describe
function, it's possible to patch spec definitions to expose needed data. A more trivial way would be to define custom wrapper function for global it
that intercepts test name.
Custom reporter is a better way to do this. Reporter interface is self-documented, necessary data is available in testResult
.
Performance measurements are already available:
module.exports = class TimeReporter {
onTestResult(test, testResult, aggregatedResult) {
for (let { title, duration } of testResult.testResults)
console.log(`test '${title}': ${duration} ms`);
}
}
Can be used like:
reporters: ['default', "<rootDir>/time-reporter.js"]
As it was noted, there are beforeAll
and afterAll
, they run once per describe
test group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With