Reactgular
Reactgular

Reputation: 54821

Rxjs observable that completes without emitting value passes unit test, but shouldn't

I have the following unit test which passes, but it shouldn't because the expected value is never emitted.

Here is a simplified example that reproduces the problem:

it('should fail but value is skipped', done => {
  of(1).pipe(
    skip(1)
  ).subscribe(
     v => expect(v).toBe(1),
     () => done.fail(),
     () => done()
  );
});

I can modify the above code to force at least one value, but the original problem is that the mistake went unnoticed for a while. It seems that Jest is happy to pass a unit test when no calls to expect() are made.

it('still passes', done => {
   done();
});

it('same here' () => {});

This becomes more difficult to spot if the observable is created externally to the test.

it('should fail but value is never emitted', done => {
  someFunction().subscribe(
     v => expect(v).toBe(1),
     () => done.fail(),
     () => done()
  );
});

The above unit test passed as expected, but a bug later made the observable complete without emitting a value, and the test still passed.

Is there a way to configure Jest to fail if expect() is never called?

If there isn't such a feature, then what can I do differently to test asynchronous code?

Upvotes: 1

Views: 762

Answers (1)

Oles Savluk
Oles Savluk

Reputation: 4345

There is method expect.assertions(number) which verifies that a certain number of assertions are called during a test.

So you can modify test like this:

it('should fail but value is never emitted', () => {
  expect.assertions(1);
  someFunction().subscribe(v => expect(v).toBe(1));
});

Upvotes: 1

Related Questions