Skip to content

Instantly share code, notes, and snippets.

@ryzy
Created August 24, 2020 10:57
Show Gist options
  • Save ryzy/fe75d493f86ad13d89bf1160079c4557 to your computer and use it in GitHub Desktop.
Save ryzy/fe75d493f86ad13d89bf1160079c4557 to your computer and use it in GitHub Desktop.
isTextContext
describe('#isTestContext', () => {
beforeEach(() => {
delete process.env.JEST_WORKER_ID;
delete (window as any).__karma__;
delete (window as any).Cypress;
});
it('#isTestContext should be true for Jest', () => {
expect(isTestContext()).toBe(false);
process.env.JEST_WORKER_ID = '1';
expect(isTestContext()).toBe(true);
});
it('#isTestContext should be true for Karma', () => {
expect(isTestContext()).toBe(false);
(window as any).__karma__ = {};
expect(isTestContext()).toBe(true);
});
it('#isTestContext should be true for Cypress', () => {
expect(isTestContext()).toBe(false);
(window as any).Cypress = {};
expect(isTestContext()).toBe(true);
});
});
/**
* Returns true if code is executed in test (i.e. Karma/Jest) context.
*/
export function isTestContext(): boolean {
const isKarma: boolean = !!(window as any).__karma__;
const isJest: boolean = 'undefined' !== typeof process && !!process.env.JEST_WORKER_ID;
const isCypress: boolean = !!(window as any).Cypress;
return isKarma || isJest || isCypress;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment