gpt4 book ai didi

javascript - Jest : Testing window. location.reload

转载 作者:可可西里 更新时间:2023-11-01 01:41:17 24 4
gpt4 key购买 nike

如何编写测试以确保方法 reloadFn 实际上重新加载窗口?我找到了 this resource但是我不清楚在给定函数中发生窗口重新加载时编写测试时如何期望窗口重新加载。感谢您的帮助!

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

最佳答案

更新答案(2021 年 11 月)

包装:“开 Jest ”:“^26.6.0”"@testing-library/jest-dom": "^5.11.4"

构建:create-react-app 4

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

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

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();
});
});

注意:更新了答案,因为 CRA 中使用的最新 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();
});
});

谢谢:)

关于javascript - Jest : Testing window. location.reload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55712640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com