使用`import`语句而不是`require`调用单个mocha测试

时间:2016-08-18 11:37:57

标签: testing reactjs

我有一个简单的测试,我想在前端测试服务及其方法。在后端,我使用require()来获取模块,但前端使用 webpack import

我的测试:

const testee = require('../network-template.service');

describe('getTemplates', function () {
    it('shall return templates from server', function (done) {
        console.log(testee);
        done();
    });
});

我的测试班:

import fetch from 'isomorphic-fetch';

const ENDPOINT = 'http://localhost:3000/api/network-templates';

class NetworkTemplateService {
    getTemplates(){
        return fetch(ENDPOINT, {
            method: 'GET',
            headers: {
                'Accept' : 'application/json'
            },
            body: JSON.stringify(ports)
        })
            .then(response => ({response}))
            .catch(error => ({error}));
    }

有一种简单快捷的方法来运行此测试吗?我喜欢在后端如何编译任何东西,并且可以在没有任何设置的情况下立即运行所有测试。

2 个答案:

答案 0 :(得分:2)

Babel有一个require()挂钩,可用于动态地转换代码,因此您无需在运行测试之前进行任何设置。

安装:

npm i babel-register --save-dev

要使用它,您可以在mocha.opts文件中添加此行:

--compilers js:babel-register

或者,您可以将其添加为命令行标志。如果您的test ...

中有package.json脚本
"scripts": {
    "test" "./node_modules/.bin/mocha --compilers js:babel-register"
}

答案 1 :(得分:0)

可能会在package.json添加此行并使用babel进行预编译。

..."scripts": {
        "test":"mocha --compilers js:babel-core/register ./test/example_test.js"
}...