unit-testing - 开 Jest mock document.referrer

标签 unit-testing jestjs

我在需要单元测试的 React 应用程序服务中有以下方法。

onDeclineCallback = () => {
    console.log("boom " + document.referrer);

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

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

history.back = jest.fn(); // Mocking history.back as jest fn

describe('age verifiction service test', () => {
  it('returns user to referrer if declined and referrer is available', () => {
    document = {
      ...document,
      referrer: 'Refferer Test', // My hacky attempt at mocking the entire document object
    };

    ageVerification.onDeclineCallback();
    expect(history.back).toHaveBeenCalledTimes(1);
  });
});

我正在尝试找到一种模拟 document.referrer 的方法,以便为每个案例编写单元测试。谁能为此提供一种方法?

最佳答案

您可以使用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

关于unit-testing - 开 Jest mock document.referrer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59198002/

相关文章:

c# - Watin 触发的 onchange 事件中的对话框

java - 如何使用测试驱动开发方法验证 boolean 方法?

reactjs - 将 Jest 与 react-scripts 一起使用(通过 yarn 运行),如何在不必传递 watchAll 标志的情况下获得完整的覆盖率报告?

javascript - 如何模拟像 new Date() 这样的构造函数

javascript - 在 webpack 4 项目中使用 Jest 会抛出 'Jest encountered an unexpected token' 错误

testing - 如何将 TestRail 与 Jest 测试集成?

angular - 如何从单元测试访问注入(inject)的 ngControl?

c# - 这是使用构造函数链接的好方法还是坏方法? (...允许测试)

javascript - 从 Jest 中获取正确的堆栈跟踪

unit-testing - 最小起订量和虚拟属性和方法