unexpected behaviors on classes when testing with jest

I’m working on some tests on my project, and have run in to some weird behaviors.

My code looks something like this:

export class Variable {
  b;

  constructor() {
    this.b = 'B';
  }

  changeValue = () => {
    this.b = 'changed B';
  };
}

export class DerivedVariable {
  v;

  constructor(v: Variable[]) {
    this.v = v;
  }
}

export class Store {
  a;

  v;

  initialize = () => {
    this.a = new Variable();
  };

  get computedValue() {
    return [this.a];
  }

  get computedInstances() {
    return new DerivedVariable(this.computedValue);
  }
}

and my test code:

test('test', () => {
    const { a, computedValue, computedInstances, initialize } = new Store();

    initialize();

    expect(computedValue[0].b).toBe('B');

    computedValue[0].changeValue();

    expect(a.b).toBe('changed B');

    expect(computedInstances.v[0].b).toBe('changed B');
  });

I figured running the initialize function would populate the class variable, which would allow the test to pass.

However, the results of the test returns something like:

 TypeError: Cannot read properties of undefined (reading 'b')

      24 |     initialize();
      25 |
    > 26 |     expect(computedValue[0].b).toBe('B');

Does jest have an asynchronous behavior when it comes to creating class instances?

Thanks in advance.

  • On a side note, I’ve run into a similar issue when testing with class variables after calling a function that mutates it, I assume the two issues are related.