不带 module.exports 的 Jest 单元测试

Nir*_*ana 4 javascript unit-testing node.js npm jestjs

我有一个包含单个const变量的脚本,该变量包含我的所有逻辑,有点像 Moment.js。
我想用 Jest 测试这个脚本的功能。

我无法使用,module.exports因为当我发布我的脚本时它不起作用。
如果我不能使用,module.exports我就不能使用require.

但我仍然想在我的脚本上运行单元测试。
我尝试使用但import没有运气。

这是我的代码:

import 'src/library.js';

test('Something', () => {
    expect(library.add(1,2)).toBe(3);
});
Run Code Online (Sandbox Code Playgroud)

这是我的图书馆:

const library = () => {
    return {
        add : (num1,num2) => num1 + num2,
        subtract : (num1,num2) => num1 - num2
    }
}
Run Code Online (Sandbox Code Playgroud)

mor*_*est 5

用以下方式包装您的出口怎么样:

if (typeof exports !== 'undefined') {
    module.exports = { yourWhatever };
}
Run Code Online (Sandbox Code Playgroud)