首页 > web前端 > js教程 > 正文

笑话回顾:安全模拟全局对象的属性和方法

PHPz
发布: 2024-07-18 21:01:07
转载
843人浏览过

笑话回顾:安全模拟全局对象的属性和方法

长话短说:

  • 您希望避免覆盖/模拟的属性/方法影响其他测试。
  • 对于本地对象(由该测试创建并拥有),您可以(并且应该)使用
    • localobject.theanswer = 42 和
    • localobject.calctheanswer = jest.fn(() => 42).
  • 对于全局对象,您应该使用
    • jest.replaceproperty(globalobject, "theanswer", 42) 和
    • jest.spyon(globalobject, "calctheanswer").mockreturnvalue(42).
  • 确保在 aftereach() 钩子中调用 jest.restoreallmocks() 。

什么?

在完美的世界代码库中,不需要操作全局对象,但是世界代码库很混乱 - 测试也是如此。

您要不惜一切代价避免一个测试影响另一个测试。无论顺序如何,或者是否跳过某些测试,测试都应该有意义。

模拟属性

模拟值的一种简单方法是将属性设置为测试中所需的任何值。
只要您更改此特定测试拥有(创建)的本地对象中的值就可以了:

describe("override properties of local objects", () => {
    it("works and is harmless", () => {
        const myarray = [1];
        myarray.length = 0;
        expect(myarray).tohavelength(0);
    });
    it("does not affect the next test", () => {
        const myarray = [1];
        expect(myarray).tohavelength(1);
    });
});
登录后复制

如果你对全局对象这样做,它会变得混乱:

describe("don't override properties of global objects", () => {
    it("works before the property is overridden", () => {
        expect(window.innerwidth).tobegreaterthan(0);
    });
    it("works, but is evil", () => {
        window.innerwidth = 0;
        expect(window.innerwidth).tobe(0);
    });
    it("fails in the test after the property was overridden", () => {
        expect(() => {
            expect(window.innerwidth).tobegreaterthan(0); // <-- error: expect(received).tobegreaterthan(expected)
        }).tothrow(error);
    });
});
登录后复制

这就是 jest.replaceproperty() 的用途:

describe("use jest.replaceproperty() to override properties of global objects", () => {
    aftereach(() => {
        jest.restoreallmocks();
    });
    it("works before the property is overridden", () => {
        expect(window.innerwidth).tobegreaterthan(0);
    });
    it("works and is harmless", () => {
        jest.replaceproperty(window, "innerwidth", 0);
        expect(window.innerwidth).tobe(0);
    });
    it("does not affect the next test", () => {
        expect(window.innerwidth).tobegreaterthan(0);
    });
});
登录后复制

模拟方法

方法可以像属性一样被模拟。

describe("override methods of local objects using jest.fn()", () => {
    it("works and is harmless", () => {
        const myset = new set([1]);
        myset.has = jest.fn().mockreturnvalue(false);
        expect(myset.has(1)).tobefalsy();
    });
    it("does not affect the next test", () => {
        const myset = new set([1]);
        expect(myset.has(1)).tobetruthy();
    });
});
登录后复制

如果你在全局对象上使用 myobject.somefunction = jest.fn() ,你的测试可能会相互依赖并失去它们的意义:

describe("don't override methods of global objects using jest.fn()", () => {
    it("works before the method is overridden", () => {
        expect(document.getelementbyid("foo")).tobenull();
    });
    it("works, but is evil", () => {
        const el = document.createelement("div");
        document.getelementbyid = jest.fn().mockreturnvalue(el);

        expect(document.getelementbyid("foo")).tobe(el);
    });
    it("fails in the test after the property was overridden", () => {
        expect(() => {
            expect(document.getelementbyid("foo")).tobenull(); // <-- error: expect(received).tobenull()
        }).tothrow(error);
    });
});
登录后复制

我们应该如何模拟全局对象中的方法?这就是 jest.spyon() 的好处:

describe("use jest.spyOn() to override methods of global objects", () => {
    afterEach(() => {
        jest.restoreAllMocks();
    });
    it("works before the method is overridden", () => {
        expect(document.getElementById("foo")).toBeNull();
    });
    it("works and is harmless", () => {
        const el = document.createElement("div");
        jest.spyOn(document, "getElementById").mockReturnValue(el);

        expect(document.getElementById("foo")).toBe(el);
    });
    it("does not affect the next test", () => {
        expect(document.getElementById("foo")).toBeNull();
    });
});
登录后复制

你必须清理

如果你想确保所有测试都发现系统处于相同(新鲜、干净)状态,则需要在每次测试后恢复模拟的状态。

最简单的解决方案是设置restoremocks配置属性。

最直接的选择是在 aftereach() 中调用 jest.restoreallmocks()

如何为所有测试模拟某些内容

有时您想模拟文件中所有测试的内容。如果您在顶层或在describe()块中使用jest.spyon()和jest.replaceproperty(),则在执行第一个测试后,所有mock将被重置。

在顶层,您可以安全地重写属性和方法,无需 jest.spyon() 和 jest.replaceproperty()。

如果您只想为describe() 块模拟事物,则需要在beforeeach() 挂钩中进行这些调用。

以上就是笑话回顾:安全模拟全局对象的属性和方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号