JavaScript test (mocha) with 'import' js file

前端 未结 2 1245
深忆病人
深忆病人 2020-12-30 05:49

I understand module.export and require mannner:

Requiring external js file for mocha testing

Although it\'s pretty usable as long a

2条回答
  •  醉梦人生
    2020-12-30 06:22

    UPDATE: FINAL ANSWER:

    My previous answer is invalid since eval(code); is not useful for variables.

    Fortunately, node has a strong mehod - vm

    http://nodejs.org/api/vm.html

    However, according to the doc,

    The vm module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult the open issues on GitHub. Some of the biggest problems are described below.

    so, although this works on the surface, extra care needed for such an purpose like testing...

    var expect = require('chai')
        .expect;
    
    var fs = require('fs');
    var vm = require('vm');
    var path = './app.js';
    
    var code = fs.readFileSync(path);
    vm.runInThisContext(code);
    
    describe('SpaceTime', function()
    {
        describe('brabra', function()
        {
            it('MEMORY === "MEMORY"',
                function()
                {
                    expect(MEMORY)
                        .to.equal('MEMORY');
                })
        });
    
    });
    

    AFTER ALL; The best way I found in this case is to write the test mocha code in the same file.

提交回复
热议问题