What is the Difference Between Describe, Test, and It in Jest?
Jest comes with three different built-in functions for organizing test cases. They are describe
, test
, and it
. Whenever you start writing your test files from an empty file you should always start with a describe
:
// Use describe to group several related tests
describe('Several related tests', () => {
// Your individual test cases will go here
})
Use describe
to create blocks that group several related tests together. Depending on your testing approach, you might have a describe
for each individual component in your application, each module, or each class.
Whichever approach you take, make sure it groups related tests together. You can also nest describe
blocks into each other to further break down your tests and improve readability if needed.
// You can nest describe into each other
describe('Sort & Filters', () => {
describe('Sorting', () => {
// Sorting related tests
})
describe('Filtering', () => {
// Filtering related tests
})
})
The test and it blocks in Jest
Use test
to execute individual test cases. Different functionality should be tested in different blocks. You should be able to describe each test with a single sentence. It's a common practice to start each block with the word "should" to describe what should happen in the block.
describe('Several related tests', () => {
test('Should execute a single test', () => { ... })
it('Should do the same as test', () => { ... })
})
describe('Filters', () => {
it('Should filter for best tutorials', () => { ... })
it('Should filter by rating', () => { ... })
it('Should filter by category', () => { ... })
})
This should be the smallest part of your test cases, you should not be able to further break down your test
blocks into smaller, multiple test
blocks.
For better organizing your test cases, make sure you define your test
blocks inside a describe
. The it
block is an alias for test
, it works exactly the same way, therefore It's only a matter of choice whether you use test
or it
.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: