Jest模拟文档. referer

cyej8jka  于 2023-03-16  发布在  Jest
关注(0)|答案(3)|浏览(179)

我在一个需要单元测试的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的方法,以便为每种情况编写一个单元测试。有人能提供一种方法吗?

9w11ddsr

9w11ddsr1#

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

jtw3ybtb

jtw3ybtb2#

为我工作,开玩笑的方式:

jest.spyOn(document, 'referrer', 'get').mockReturnValue('mock ref value');
ewm0tg9j

ewm0tg9j3#

Object.defineProperty(document, 'referrer', {
    value: 'test.com',
    writable: true,
  });

相关问题