JavaScript test (mocha) with 'import' js file

£可爱£侵袭症+ 提交于 2019-12-18 12:22:08

问题


I understand module.export and require mannner:

Requiring external js file for mocha testing

Although it's pretty usable as long as it's a module, I feel this manner is inconvenient since what I intends to do now is to test a code in a file.

For instance, I have a code in a file:

app.js

'use strict';
console.log('app.js is running');
var INFINITY = 'INFINITY';

and now, I want to test this code in a file:

test.js

var expect = require('chai').expect;

require('./app.js');


    describe('INFINITY', function()
    {
        it('INFINITY === "INFINITY"',
            function()
            {
                expect(INFINITY)
                    .to.equal('INFINITY');
            });
    });

The test code executes app.js, so the output is;

app.js is running

then

ReferenceError: INFINITY is not defined

This is not what I expected.

I do not want to use module.export and to write like

var app = require('./app.js');

and

app.INFINITY and app.anyOtherValue for every line in the test code.

There must be a smart way. Could you tell me?

Thanks.


回答1:


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.




回答2:


I usually include a _test object containing references to all my "private" internal variables and functions and expose it on exports. In your case:

./app.js

var INFINITY = 'infinity';

function foo() {
    return 'bar';
}

exports._test = {
    INFINITY: INFINITY,
    foo: foo
}

./test/app-test.js

var app = require('../app.js')
/* ... */
it('should equal bar', function() {
    expect(app._test.foo()).to.equal('bar');
});
it('should equal infinity', function() {
    expect(app._test.INFINITY).to.equal('infinity');
});


来源:https://stackoverflow.com/questions/21421701/javascript-test-mocha-with-import-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!