A describe()
block is a function that takes two arguments:
- the name (string)
- a function that contains other
describe()
blocks or the actual tests.
The same applies for both Vitest and Jest.
Here is a made-up example where we have a class (referenced as service
), and we are splitting up the tests for each public method:
getBlogPosts()
createBlogPost()
Within these describe blocks we can have multiple tests (and each test()
function itself can have multiple assertions)
describe('getBlogPosts()', () => {
test('it gets blog posts', () => {
expect(
service.getBlogPosts()
).toHaveLength(1);
});
test('gets archived posts', () => {
expect(
service.getBlogPosts({
archived: true,
})
).toHaveLength(2);
});
});
describe('createBlogPost()', () => {
test('it creates a blog post', async () => {
expect(
await service.createBlogPost({
title: 'Hello',
})
).toBe(true);
});
});
You can nest your describe()
blocks. It is a very common pattern to have a single outer describe
block (although really it often doesn't add much value).
describe('BlogService', () => {
describe('getBlogPosts()', () => {
describe('when posts exist', () => {
test('it gets blog posts', () => {
expect(
service.getBlogPosts()
).toHaveLength(1);
});
});
describe('when no posts exist', () => {
test('returns empty array', () => {
expect(
service.getBlogPosts()
).toHaveLength(0);
});
});
});
});
We will have a future lesson on setup and teardown functions, but just in case you wanted to see the syntax now, you can use beforeAll
, beforeEach
, afterEach
and afterAll
within describe blocks.
Each hook runs either once for all tests in that describe block, or once for each test (again within that describe block), depending on which one you use.
describe('createBlogPost()', () => {
let service;
beforeAll(() => {
service = new BlogService();
});
beforeEach(() => {
service.clearDatabase();
});
afterEach(() => {
service.resetState();
});
test('it creates a blog post', async () => {
expect(
await service.createBlogPost({
title: 'Hello',
})
).toBe(true);
});
});
If this is not clear- wait until we get to a future lesson just on this topic!
Lesson Task
Using the test runner (use the tabs aboveon the right), place your test()
calls inside describe()
blocks.
- The first argument is a name. It can be any string.
- The second argument is a function containing your tests.
- You can nest multiple
describe()
blocks inside another one.