How to access and test an internal (non-exports) function in a node.js module?

后端 未结 8 2006
别跟我提以往
别跟我提以往 2020-12-12 09:31

I\'m trying to figure out on how to test internal (i.e. not exported) functions in nodejs (preferably with mocha or jasmine). And i have no idea!

Let say I have a mo

8条回答
  •  渐次进展
    2020-12-12 09:51

    Essentially you need to merge the source context with the test cases - one way to do this would be using a small helper function wrapping the tests.

    demo.js

    const internalVar = 1;
    
    

    demo.test.js

    const importing = (sourceFile, tests) => eval(`${require('fs').readFileSync(sourceFile)};(${String(tests)})();`);
    
    
    importing('./demo.js', () => {
        it('should have context access', () => {
            expect(internalVar).toBe(1);
        });
    });
    
    

提交回复
热议问题