191

When writing a unit test in Jest or Jasmine when do you use describe?

When do you use it?

I usually do

describe('my beverage', () => {
  test('is delicious', () => {
  });
});

When is it time for a new describe or a new it?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Brown Limie
  • 2,249
  • 3
  • 17
  • 18

4 Answers4

235

describe breaks your test suite into components. Depending on your test strategy, you might have a describe for each function in your class, each module of your plugin, or each user-facing piece of functionality.

You can also nest describes to further subdivide the suite.

it is where you perform individual tests. You should be able to describe each test like a little sentence, such as "it calculates the area when the radius is set". You shouldn't be able to subdivide tests further-- if you feel like you need to, use describe instead.

describe('Circle class', function() {
  describe('area is calculated when', function() {
    it('sets the radius', function() { ... });
    it('sets the diameter', function() { ... });
    it('sets the circumference', function() { ... });
  });
});
David Schumann
  • 13,380
  • 9
  • 75
  • 96
Interrobang
  • 16,984
  • 3
  • 55
  • 63
102

As I mentioned in this question, describe is for grouping, it is for testing.

As the jest docs says, test and it are the same: https://jestjs.io/docs/en/api#testname-fn-timeout

test(name, fn, timeout)

Also under the alias: it(name, fn, timeout)

and describe is just for when you prefer your tests to be organized into groups: https://jestjs.io/docs/en/api#describename-fn

describe(name, fn)

describe(name, fn) creates a block that groups together several related tests. For example, if you have a myBeverage object that is supposed to be delicious but not sour, you could test it with:

const myBeverage = {
  delicious: true,
  sour: false,
};

describe('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

This isn't required - you can write the test blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups.

SeyyedKhandon
  • 5,197
  • 8
  • 37
  • 68
4

I consider this more from the impact on the test output. By using describe or multiple levels of describe you can group your output for readability.

MattG
  • 5,589
  • 5
  • 36
  • 52
0

Think simple that describe is group and it or test is really unit test.

So, describe can be nested in describe but it isn't.

Doan Thai
  • 561
  • 3
  • 10