【问题标题】:How to export functions from a module to be tested with npm jest?如何从要使用 npm jest 测试的模块中导出函数?
【发布时间】:2022-11-11 06:01:54
【问题描述】:

总体问题:我很早就开始学习 TDD。到目前为止,我使用 npm 和 jest 来运行我的测试。我有一个测试脚本,它与 2 个虚拟函数一起工作得很好,这些虚拟函数既写成显式命名函数,又写成工厂函数。但是,我正在尝试编写更多代码,将我的大部分功能包装在模块中,以使它们更有条理和由于某种原因,我无法开玩笑地测试模块内部的功能。

我所期望的:

$npm run test main.test.js
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total

我得到的是:

$npm run test main.test.js

TypeError: "TypeError: test2module.test2 is not a function"
Test Suites: 1 failed, 1 total
Tests:       2 failed, 1 passed, 3 total

main.js 测试代码:

//this code passes the test
const test1=(text)=>{
    text += " and goofy";
    return text;
}

//this module and the fucntion inside of it is the one I'm having trouble with. 
const test2module = (()=>{
    const test2 = (num) =>{
        let myNum = num;
        myNum ++;
        return myNum;
    };

    return {test2};
})
    



//no code beyond this line
module.exports = {test1, test2module};

main.test.js 测试代码:

const {test1, test2module} = require("./main");

test("does test1 add goofy?",()=>{
    expect(test1("donald")).toBe('donald and goofy');

});

describe("does test2 increment?", ()=> {
    test("6 should become 7", () =>{
        expect(test2module.test2(6)).toBe(7);
    });

    test("1 should become 2", () => {
        expect(test2module.test2(1)).toBe(2);
    });
});

【问题讨论】:

    标签: javascript unit-testing module jestjs tdd


    【解决方案1】:

    解决方案:test2module 缺少另一组 ();最后。所以它实际上并没有完全写出来,我认为这造成了语法错误。

    当您实际关闭函数时,代码运行并通过测试就好了:

    const test2module = (()=>{
        const test2 = (num) =>{
            let myNum = num;
            myNum ++;
            return myNum;
        };
    
        return {test2};
    })();
    

    果然,我在写问题时解决了它。 (一定要喜欢橡皮鸭)。 与其删除我所有的工作,我想我还是把它和答案一起发布,以防万一其他人将来遇到这个特定问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 2020-06-05
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多