question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Bug]: Test Suite Fail with `jest.isolateModules` when upgrading to 27.4.5

See original GitHub issue

Version

27.4.5

Steps to reproduce

This code snippet

foo.ts
const deploymentLoggers: Logger[] = [];

export const createDeploymentLogger = async (request: DeploymentLoggerArgs): Promise<Logger> => {
    ...
    deploymentLoggers.push(logger);
    return logger;
};

const closeLogger = async (logger: Logger) => {
    const closeDynamoTransports = logger.transports
        .filter(transport => transport instanceof WinstonDynamoDB)
        .map(transport => new Promise<void>(resolve => (transport as WinstonDynamoDB).kthxbye(() => resolve())));

    const closeCloudwatchTransports = flushCloudwatchTransport(logger);

    await Promise.all([...closeDynamoTransports, closeCloudwatchTransports]);
    logger.close();
};

export const closeAllDeploymentLoggers = async () => {
    const promises = [];
    while (deploymentLoggers.length) {
        const logger = deploymentLoggers.pop();
        promises.push(closeLogger(logger));
    }
    await Promise.all(promises);
};

foo.spec.ts
describe('closeAllDeploymentLoggers', () => {
    let cloudwatchTransportSpy;
    let flushCloudwatchTransportSpy;
    let createDeploymentLogger
    let loggers;
    beforeEach(() => {
        jest.isolateModules(() => {
            ({ closeAllDeploymentLoggers, createDeploymentLogger } = require('foo'));
        });
    });

    beforeEach(async () => {
        flushCloudwatchTransportSpy = jest.spyOn(CloudwatchLogger, 'flushCloudwatchTransport').mockResolvedValue(undefined);
        loggers = [];
        loggers.push(await createDeploymentLogger(loggerParams));
        loggers.push(await createDeploymentLogger({ ...loggerParams, logStreamName: 'le-log-stream-2' }));

        await closeAllDeploymentLoggers();
    });

    it('should flush cloudwatch logs of all loggers', () => {
        expect(flushCloudwatchTransportSpy).toHaveBeenCalledTimes(loggers.length);
    });
});

When running this test i’m getting

Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 2
Received number of calls: 0

it seems when using jest.isolateModules it “detach” from the last run and not counting the calls in the new version of jest, unlike the previous version where jest count those calls.

The reason we use jest.isolateModules is to reset the deploymentLoggers variable so we need to reimport the package each time, when we change to jest.mock in order to mock the deploymentLoggers and reset it each time the test pass, but i need to jest.requireActual the reset of the module…

this is a breaking change in the way jest.isolateModules works

Expected behavior

It should work in the new version (jest 27.4.5 with ts-jest 27.1.1) as it works in jest version 26.6.3 with ts-jest 26.5.6

Actual behavior

Jest not counting the spyOn calls when using isolateModules

Additional context

No response

Environment

System:
  OS: macOS 12.0.1
  CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Binaries:
  Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
  Yarn: 6.7.6 - /usr/local/bin/yarn
  npm: 6.14.13 - ~/.nvm/versions/node/v14.17.0/bin/npm

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:3
  • Comments:13

github_iconTop GitHub Comments

2reactions
SimenBcommented, Dec 15, 2021

It should work in the new version (jest 27.4.5 with ts-jest 27.1.1) as it works in jest version 26.6.3 with ts-jest 26.5.6

Why? All I’m seeing in this bug report is “my test is now failing”, I don’t see how Jest’s current behaviour is incorrect. I assume the change you’re hitting is https://github.com/facebook/jest/pull/10963, which is definitely a bug fix - isolateModules should return a fresh instance of a module, not the old one.

Can you put together a minimal example (e.g. without typescript, and preferably just a minimal file and minimal test) for us to look at, that passes with v26 and fails with v27? Easier to judge if the behaviour should be considered a bug or not then. 🙂

1reaction
yaronyacommented, Dec 20, 2021

Just import the logger inside the same isolateModules and mock it there

This might be a workaround, but I believe it’s legitimate to expect the library to not fail on those scenarios.

Either way, this is not a bug in v27, so closing this.

I strongly disagree here. I’ve upgraded to v27 from v26 and things started failing w/o any code change. I don’t know how to call it other than “bug”…

Read more comments on GitHub >

github_iconTop Results From Across the Web

@jest/create-cache-key-function | Yarn - Package Manager
This module creates a function which is used for generating cache keys used by code transformers in Jest. Install. $ npm install --save-dev...
Read more >
Mocking different values for the same module using Jest
Module mocks are a powerful tool to write unit tests with Jest. They allow you to isolate the code under test from its...
Read more >
jest mock cannot access before initialization - You.com
Clone the repo https://github.com/dnbtr/jest-test-bug ;; Run $ npm install to install dependencies;; Run tests with $ npm test . Expected behavior. Two tests...
Read more >
Jest 27: New Defaults for Jest, 2021 edition
Everyone on the new defaults can benefit from a smaller install size, ... can now also be used to step through failed tests...
Read more >
@jest/core: Versions | Openbase
[docs] Update link to Jest 28 upgrade guide in error message (#13483) ... jest-config] A seed for the test run will be randomly...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found