gpt4 book ai didi

javascript - 如何处理影响 Jest 中其他测试的全局对象/测试

转载 作者:行者123 更新时间:2023-12-01 03:47:26 24 4
gpt4 key购买 nike

我在 React Native 项目中的一些测试会影响全局对象。这些更改通常会影响依赖相同对象的其他测试。

例如:一个测试检查监听器是否正确添加,第二个测试检查监听器是否正确删除:

// __tests__/ExampleClass.js
describe("ExampleClass", () => {
it("should add listeners", () => {
ExampleClass.addListener(jest.fn());
ExampleClass.addListener(jest.fn());

expect(ExampleClass.listeners.length).toBe(2);
});
it("should remove listeners", () => {
const fn1 = jest.fn();
const fn2 = jest.fn();
ExampleClass.addListener(fn1);
ExampleClass.addListener(fn2);

expect(ExampleClass.listeners.length).toBe(2);

ExampleClass.removeListener(fn1);

expect(ExampleClass.listeners.length).toBe(1);

ExampleClass.removeListener(fn2);

expect(ExampleClass.listeners.length).toBe(0);
});
});

第二个测试本身可以正常运行,但是当所有测试都运行时就会失败,因为第一个测试没有清理ExampleClass。我是否总是需要在每次测试中手动清理这样的东西?

我似乎不明白范围在 Jest 中是如何工作的...我假设每个测试都会在新环境中运行。有这方面的文档吗?

其他示例是模拟外部库并检查其中的模拟函数是否被正确调用,或者将 Platform.OS 覆盖到 ios 或 android 以测试特定于平台的实现。

最佳答案

据我所知,测试的范围始终是测试文件。现在,我将代码更改为具有 beforeEach 回调,主要调用 jest.resetAllMocks() 并将 Platform.OS 重置为其默认值。

Fast and sandboxed

Jest parallelizes test runs across workers to maximize performance. Console messages are buffered and printed together with test results. Sandboxed test files and automatic global state resets for every test so no two tests conflict with each other.

https://facebook.github.io/jest/

关于javascript - 如何处理影响 Jest 中其他测试的全局对象/测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43475276/

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