我有一个简单的测试,我想在前端测试服务及其方法。在后端,我使用 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}));
}
有没有一种简单快速的方法来运行这个测试?我喜欢在后端我不编译任何东西并且可以立即运行所有测试而无需任何设置。
最佳答案
Babel 有一个 require()
Hook ,可用于动态转换代码,因此您无需在运行测试之前进行任何设置。
安装:
npm i babel-register --save-dev
要使用它,您可以在 mocha.opts
文件中添加以下行:
--compilers js:babel-register
或者,您可以将其添加为命令行标志。如果您的 package.json
中有一个 test
脚本...
"scripts": {
"test" "./node_modules/.bin/mocha --compilers js:babel-register"
}
关于testing - 使用 `import` 语句而不是 `require` 调用单个摩卡测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39017237/