Stav Alfi
Stav Alfi

Reputation: 13923

Assert That "expect" Called X Times in Jest

How can I fail the test if expect was not called at all? Or even better, when it was not called X times?

For example:

it('should fail', () => {
    if (1 === 2) {
        expect(1).toEqual(1)
    }
}

In other words, what is the equivalent of ava-t.plan in Jest?

Upvotes: 2

Views: 1018

Answers (1)

Remolten
Remolten

Reputation: 2682

You can use expect.hasAssertions() to ensure an assertion was made:

it('made an assertion', () => {
    expect.hasAssertions();
    if (1 === 2) {
        expect(1).toEqual(1)
    }
}

In this case, the test would fail because expect is never called.

You can also use expect.assertions(...) to ensure a specific number of assertions were made in your test. This test will pass:

it('made 2 assertions', () => {
    expect.assertions(2);
    expect(1).toEqual(1);
    expect(2).toEqual(2);
}

See the Jest documentation on expect for more information.

Upvotes: 4

Related Questions