Home > database >  Jest test is not executed in order when debugging
Jest test is not executed in order when debugging

Time:10-11

I just came across a very strange behavior while writing tests in a TypeScript project using jest and PhpStorm.

I've made a simplified example to illustrate the problem:

enter image description here

To explain what's going on:

I run the test 3 times:

  1. The first time with all the lines and the debugger, it fails on line 14 where it should not, because mutated should still be false at this point.

  2. The second time with the line 15 commented out and the debugger. It succeeds the where it failed before.

  3. With all the lines but without the debugger, it succeeds.

So the point here is not to discuss if it's good or bad to have a mutation in a getter.

The point is to understand why the line 15 is executed before the line 14 when the debugger is active?

I put the code below so you can read it more easily:

class Foo {
    public mutated: boolean = false;

    public get getMe(): string {
        this.mutated = true;
        return 'me';
    }
}

test('state of mutated', () => {
    const foo = new Foo();
    expect(foo.mutated).toEqual(false);
    expect(foo.getMe).toEqual('me');
    expect(foo.mutated).toEqual(true);
});

Thanks for your help.

CodePudding user response:

It's not a problem with execution order - the calls are executed in the right order. That's a different issue: with Enable auto expressions in Variables view enabled in Settings | Build, Execution, Deployment | Debugger | Data Views, the debugger tries to evaluate expressions to calculate variables values once a breakpoint is hit. So it evaluates foo.getMe - as a result, foo.mutated becomes true and the test fails.

I'm not sure if this can be treated as a bug or expected behavior. I can only suggest disabling this option when dealing with code like yours

  • Related