如何避免 Jest 警告:"describe" 回调不能 return 值?

How to avoid Jest warnings: A "describe" callback must not return a value?

将 Jest 从版本 23 升级到版本 24 后,当 运行 我的测试时,我几乎每次测试都会收到这样的警告消息:

A "describe" callback must not return a value. Returning a value from "describe" will fail the test in a future version of Jest.

附带的堆栈跟踪指向此模块:

addSpecsToSuite (node_modules/jest-jasmine2/build/jasmine/Env.js:443:15)

这样做的原因是我喜欢在测试中使用箭头函数的简写版本,当函数体只包含一个语句时省略花括号,例如:

describe('true', () =>
    it('should be truthy', () =>
        expect(true).toBeTruthy()));

it 声明显然 returns 不同于 undefined 的东西,因此警告。

我找到了两种解决方法:

① 不要使用Shorthand箭头函数

describe('true', () => {
    it('should be truthy', () =>
        expect(true).toBeTruthy());
});

② 使用void强制返回未定义

describe('true', () =>
    void it('should be truthy', () =>
        expect(true).toBeTruthy()));

我觉得这两个选项都不可接受,我不想重构成千上万的测试只是为了让 Jest(或 Jasmine)开心。

所以我的问题是:

有没有一种方法可以配置 Jest,以便在使用 shorthand 箭头函数时不会发出这些警告?

我想如果你真的想保留现有的测试语法并且只是想避免警告你可以这样做:

const realDescribe = describe;
describe = ((name, fn) => { realDescribe(name, () => { fn(); }); });

只需将该代码添加到您的 setupFilesAfterEnv 中包含的模块中,它将 运行 "immediately after the test framework has been installed in the environment" 和 "before each test".

上面的代码将全局 describe 设置为调用真实 describe 的函数,但将 function 参数包装在不 [=24= 的匿名函数中] 随便。

如果您使用 Jest v24 无法识别的全局函数,也会出现此问题。我正在将一些 Mocha 测试转换为 Jest,而 Mocha 的 before() 抛出了同样的错误:

A "describe" callback must not return a value. Returning a value from "describe" will fail the test in a future version of Jest.

堆栈跟踪指向 describe() 是罪魁祸首,但修复是将嵌套的 before() 调用转换为兼容 Jest 的 beforeAll()。这里可能有一个与尝试使用 it() 而不是 test() 相关的问题,但这可能很重要,在 Jest 的测试环境中肯定有一个 it()

可能与 describe 回调中抛出的未处理异常有关。 例如,当我想访问不存在的成员的模拟时(在测试块之外):

logger.info1111.mockImplementation((m, d) => console.info(m, d));