Skip to content

[Bug]: expect.hasAssertions() resturns true even if expect() as not evaluated #15484

@GeroldSchierholz

Description

@GeroldSchierholz

Version

29.5.0

Steps to reproduce

If you test an observable, you would like to ensure, that the expect() assertion is actually executed and evaluated. Based on the docu, this can be achieved by calling expect.hasAssertions()

In the first example below you see, that the "toEqual" assertion is FALSE. Nevertheless the Test runs through and shows green.

The second test('not a bug') is just to show, that this bug is NOT about the expect() assertion in the subscribe block and how to solve testing observables' BUT about the "hasAssertion()" which should fail in the first test.

test('bug',` () => {
  const x = new ReplaySubject();
  expect.hasAssertions() //OK - ALTHOUGH EXPECT IS INCORRECT AND NOT EVALUATED OR EVALUATED TOO LATE
  x.next("CORRECT")
  x.subscribe( val => {
    expect(val).toEqual("WRONG") //NOT EVALUATED OR EVALUATED TOO LATE
  })
});

//WORKING SOLUTION  - BUT NOT SOLVING THE PROBLEM
test('not a bug', (done) => {
  const x = new ReplaySubject();
  expect.hasAssertions()
  x.next("CORRECT")
  x.subscribe( val => {
    expect(val).toEqual("WRONG") //EVALUATED
    done()
  })
}); 

Expected behavior

Both tests fail.
First one with expect.hasAssertions() failing.

Second one with expect.toEqual failing.

Actual behavior

First test is green (wrong).
Second red (as expected).

Additional context

No response

Environment

jest 29.5.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions