具有“导入" js文件的JavaScript测试(摩卡) [英] JavaScript test (mocha) with 'import' js file

查看:67
本文介绍了具有“导入" js文件的JavaScript测试(摩卡)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解module.exportrequire曼纳:

需要外部js文件进行摩卡测试

尽管只要是模块就可以使用,但是我觉得这种方式很不方便,因为我现在打算做的是测试文件中的代码.

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');
            });
    });

测试代码执行app.js,所以输出为;

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

app.js is running

然后

ReferenceError: INFINITY is not defined

这不是我期望的.

我不想使用module.export并像这样写

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

app.INFINITYapp.anyOtherValue用于测试代码中的每一行.

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

必须有一个聪明的方法.你能告诉我吗?

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

谢谢.

推荐答案

更新:最终答案:

我的上一个答案无效,因为eval(code);对变量没有用.

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

幸运的是,node具有很强的方法-vm

Fortunately, node has a strong mehod - vm

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

但是,根据文档,

vm模块有许多已知问题和极端情况.如果您遇到问题或意外行为,请查阅GitHub上的未解决问题.以下是一些最大的问题.

因此,尽管这在表面上可行,但是需要诸如测试之类的目的进行额外的护理...

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.

这篇关于具有“导入" js文件的JavaScript测试(摩卡)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆