开玩笑:测试 window.location.reload

2024-01-03

我如何编写一个测试来确保该方法reloadFn实际上会重新加载窗口吗?我发现这个资源 https://gist.github.com/remarkablemark/5cb571a13a6635ab89cf2bb47dc004a3但我不清楚当窗口重新加载发生在给定函数中时,在编写测试时如何期望窗口重新加载。谢谢您的帮助!

const reloadFn = () => {
  window.location.reload();
}

更新答案(2021 年 11 月)

包裹:"jest": "^26.6.0" "@testing-library/jest-dom": "^5.11.4"

Build: create-react-app 4

describe("test window location's reload function", () => {
  const original = window.location;

  const reloadFn = () => {
    window.location.reload();
  };

  beforeAll(() => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: { reload: jest.fn() },
    });
  });

  afterAll(() => {
    Object.defineProperty(window, 'location', { configurable: true, value: original });
  });

  it('mocks reload function', () => {
    expect(jest.isMockFunction(window.location.reload)).toBe(true);
  });

  it('calls reload function', () => {
    reloadFn(); // as defined above..
    expect(window.location.reload).toHaveBeenCalled();
  });
});

注意:更新了答案,因为old answerCRA 中使用的最新 jest 版本不支持。


旧答案

这是解决方案,但为了更好的组织而进行了重构:

describe('test window location\'s reload function', () => {
  const { reload } = window.location;

  beforeAll(() => {
    Object.defineProperty(window.location, 'reload', {
      configurable: true,
    });
    window.location.reload = jest.fn();
  });

  afterAll(() => {
    window.location.reload = reload;
  });

  it('mocks reload function', () => {
    expect(jest.isMockFunction(window.location.reload)).toBe(true);
  });

  it('calls reload function', () => {
    reloadFn(); // as defined above..
    expect(window.location.reload).toHaveBeenCalled();
  });
});

谢谢 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

开玩笑:测试 window.location.reload 的相关文章

随机推荐