jest-preset-angular
jest-preset-angular copied to clipboard
[Discussion]Support jest.useFakeTimers and fakeAsync()
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.
-
jest.runAllTicks()
will callflushMicrotasks()
. -
jest.runAllTimers()
will callflush()
. -
jest.advanceTimersByTime()
will calltick()
-
jest.runOnlyPendingTimers()
will callflushOnlyPendingTimers()
-
jest.advanceTimersToNextTimer()
will calltickToNext()
-
jest.clearAllTimers()
will callremoveAllTimers()
-
jest.getTimerCount()
will callgetTimerCount()
For detail usage, please refer to the test file
https://github.com/angular/angular/pull/39016/files#diff-53fe8d9816dc08e106333ff822445d7fR103-R413
I left a comment for that PR. In general, README
here should be updated later related to that PR.
This solve my issues with fakeAsync and rxjs. Thanks!
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('|')})`],
};
any updates on this?
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.
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.