开玩笑的嘲笑document.referrer

时间:2019-12-05 15:06:57

标签: unit-testing jestjs

我在React App服务中有以下方法,需要进行单元测试。

function callbackDoSomething() {}
customConfirm(callbackDoSomething);

我的单元测试当前看起来像:

    Dim dt As Date = Date.Parse(TimeStamp.Text)
    Dim dateString = dt.ToString("MM/dd/yyyy")

我试图找到一种模拟onDeclineCallback = () => { console.log("boom " + document.referrer); if (document.referrer === "") { console.log("redirect to our age policy page"); } else { history.back(); } }; 的方法,以便为每种情况编写单元测试。谁能为此提供一种方法?

1 个答案:

答案 0 :(得分:0)

您可以使用Object.defineProperty方法将模拟值设置为document.referrer

例如 index.ts

export class AgeVerification {
  public onDeclineCallback = () => {
    console.log('boom ' + document.referrer);

    if (document.referrer === '') {
      console.log('redirect to our age policy page');
    } else {
      history.back();
    }
  };
}

index.spec.ts

import { AgeVerification } from './';

describe('age verifiction service test', () => {
  let ageVerification;
  beforeEach(() => {
    ageVerification = new AgeVerification();
    history.back = jest.fn();
  });
  afterAll(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  it('returns user to referrer if declined and referrer is available', () => {
    const originalReferrer = document.referrer;
    Object.defineProperty(document, 'referrer', { value: 'Refferer Test', configurable: true });
    ageVerification.onDeclineCallback();
    expect(history.back).toHaveBeenCalledTimes(1);
    Object.defineProperty(document, 'referrer', { value: originalReferrer });
  });

  it('should print log', () => {
    const logSpy = jest.spyOn(console, 'log');
    ageVerification.onDeclineCallback();
    expect(logSpy.mock.calls[0]).toEqual(['boom ']);
    expect(logSpy.mock.calls[1]).toEqual(['redirect to our age policy page']);
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/59198002/index.test.ts (13.915s)
  age verifiction service test
    ✓ returns user to referrer if declined and referrer is available (17ms)
    ✓ should print log (3ms)

  console.log src/stackoverflow/59198002/index.ts:264
    boom Refferer Test

  console.log node_modules/jest-mock/build/index.js:860
    boom 

  console.log node_modules/jest-mock/build/index.js:860
    redirect to our age policy page

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        15.385s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59198002

相关问题