'Jest testEnvironment: expect is not defined

I'm using Jest 26.x and I defined a custom testEnvironment as so:

import type { EnvironmentContext } from '@jest/environment';
import { Config } from '@jest/types';
import JSDOMEnvironment from 'jest-environment-jsdom';

declare global {
  function expectAndMore<ExpectedObject>(
    result: ExpectedObject,
    expectedObject: ExpectedObject,
  ): void;
}

class ApprovalTestEnvironment extends JSDOMEnvironment {
  constructor(config: Config.ProjectConfig, context: EnvironmentContext) {
    super(config, context);
  }

  async setup() {
    await super.setup();

    this.global.expectAndMore = ({ result, expectedObject }) => {
      expect(result).toEqual(expectedObject);
    };
  }

  async teardown() {
    await super.teardown();
  }

  getVmContext() {
    return super.getVmContext();
  }
}

export default ApprovalTestEnvironment;

I then configured a unit test file with these comments at the header of my file so it would use the custom environment defined above:

/**
 * @jest-environment ./src/approvals/approvalTestEnvironment.ts
 */

But whenever I'm trying to access the expectAndMoreFunction defined in my custom environment with globalThis.expectObjectForPostRequest(result, expected);, I get the following error:

ReferenceError: expect is not defined

Does anyone what causes this and how to fix it?

Note: I'm also using ts-jest 27.1.4.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source