thymikee / jest-preset-angular

Jest configuration preset for Angular projects.
https://thymikee.github.io/jest-preset-angular/
MIT License
885 stars 306 forks source link

[Discussion]Support jest.useFakeTimers and fakeAsync() #520

Open JiaLiPassion opened 4 years ago

JiaLiPassion commented 4 years ago

I created a PR in the angular repo https://github.com/angular/angular/pull/39016 to support integration between fake timer APIs of jest and fakeAsync().

Any feedback is appreciate!


After enable this feature, calling jest.useFakeTimers() will make all test run into fakeAsync() automatically.

beforeEach(() => {
    jest.useFakeTimers('modern');
  });
  afterEach(() => {
    jest.useRealTimers();
  });

  test('should run into fakeAsync() automatically', () => {
    const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
    expect(fakeAsyncZoneSpec).toBeTruthy();
  });

Also there are mappings between jest and zone APIs.

For detail usage, please refer to the test file

https://github.com/angular/angular/pull/39016/files#diff-53fe8d9816dc08e106333ff822445d7fR103-R413

ahnpnl commented 4 years ago

I left a comment for that PR. In general, README here should be updated later related to that PR.

Wykks commented 3 years ago

This solve my issues with fakeAsync and rxjs. Thanks!

markusmo commented 1 year ago

I saw that this is already merged with Angular. But my issue is, that the example test provided in this thread does not work for me.

could it be reagarding my jest.config.js:

module.exports = {
    extensionsToTreatAsEsm: ['.ts'],
    globals: {
        'ts-jest': {
            useESM: true,
            tsconfig: '<rootDir>/src/tsconfig.spec.json',
            stringifyContentPathRegex: '\\.(html|svg)$',
        },
    },
    moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
    moduleNameMapper: {
        '@shared/(.*)': '<rootDir>/src/app/shared/$1',
    },
    transform: {
        '^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular',
    },
    testEnvironment: 'jsdom',
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts', 'jest-extended/all', 'jest-marbles'],
    reporters: ['jest-spec-reporter'],
    transformIgnorePatterns: [`<rootDir>/node_modules/(?!.*\\.mjs$|${['@angular', '@ngrx', 'd3'].join('|')})`],
};
dedalusMohantyMa commented 9 months ago

any updates on this?

johncrim commented 8 months ago

I have tried this as well, and I'm pretty sure it doesn't work any more. Or at least, it doesn't work for ESM tests. You could try switching to CJS/non ESM mode and see if it works in that scenario with latest dependencies. Or you could just add fakeAsync() to your test methods.

dedalusMohantyMa commented 8 months ago

I already use fakeAsync everywhere, I was happy to get rid of it and create blocks where I can test components without it :-) Seems like I have to investigate some time to reconfigure.