Skip to content

Instantly share code, notes, and snippets.

@ryzy
Created August 24, 2020 10:57
Show Gist options
  • Select an option

  • Save ryzy/fe75d493f86ad13d89bf1160079c4557 to your computer and use it in GitHub Desktop.

Select an option

Save ryzy/fe75d493f86ad13d89bf1160079c4557 to your computer and use it in GitHub Desktop.

Revisions

  1. ryzy created this gist Aug 24, 2020.
    22 changes: 22 additions & 0 deletions spec.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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);
    });
    });
    9 changes: 9 additions & 0 deletions test-utils.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    /**
    * 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;
    }