简体   繁体   English

在没有模块的情况下使用Jest进行单元测试

[英]Unit testing with Jest without module.exports

I have a script that holds a single const variable which holds all of my logic, kind-of like Moment.js. 我有一个脚本,其中包含一个const变量,该变量包含我的所有逻辑,有点像Moment.js。
I want to test out functions that go out with this script with Jest. 我想用Jest测试该脚本附带的功能。

I can't use module.exports since it will not work when I publish my script. 我无法使用module.exports因为在发布脚本时它将无法正常工作。
And if I can't use module.exports I can't use require . 如果我不能使用module.exports ,就不能使用require

But I still want to run unit tests on my script. 但是我仍然想在脚本上运行单元测试。
I have tried using import with no luck. 我尝试使用import没有运气。

Here is my code: 这是我的代码:

import 'src/library.js';

test('Something', () => {
    expect(library.add(1,2)).toBe(3);
});

And this is my library: 这是我的图书馆:

const library = () => {
    return {
        add : (num1,num2) => num1 + num2,
        subtract : (num1,num2) => num1 - num2
    }
}

First Option (Quick & Dirty): Don't import. 第一选择(快速和肮脏):不导入。 Just move the code into one file. 只需将代码移到一个文件中即可。

Second Option (Best Long Term): Learn how to use (webpack and) babel . 第二种选择(最佳长期):了解如何使用(webpack和) babel

what about wrapping your exports with: 如何用以下内容包装您的出口:

if (typeof exports !== 'undefined') {
    module.exports = { yourWhatever };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM