【发布时间】:2017-11-14 21:27:11
【问题描述】:
我有一个项目,它设置为使用 react 和 jsx 构建。使用node_modules/webpack/bin/webpack.js --config webpack.config.js 构建它可以正常工作,我可以在浏览器中毫无问题地运行结果。但是,当我运行 npm test 并在浏览器中查看测试运行程序时,我收到错误:"Uncaught ReferenceError: require is not defined at dashboard-tests.js:3"。似乎 webpack 正在将我的测试(但不是我的普通代码)编译成无法在浏览器中运行的 javascript 版本。
以下是相关文件:
.babelrc:
{
"presets": ["es2015", "react"]
}
testem.json:
{
"framework": [
"jasmine"
],
"launch_in_dev": [
"PhantomJS"
],
"launch_in_ci": [
"PhantomJS"
],
"serve_files": [
"tmp/**/*-test{,s}.js"
],
"on_start": "babel static_source --out-dir tmp",
"on_exit": "yes | rm -r tmp"
}
package.json:
{
"main": "index.js",
"scripts": {
"test": "testem"
},
"dependencies": {
"jquery": "^3.2.1",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-feather": "^1.0.7"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"jasmine-es6": "^0.4.3",
"testem": "^1.18.4",
"webpack": "^3.6.0"
}
}
webpack.config.js:
var path = require("path");
var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: './static_source/js/index.js',
output: {
path: path.resolve('./app/static/js/'),
filename: "compiled.js"
},
plugins: [],
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ }
],
}
}
仪表板测试:
import React from 'react';
import ReactDOM from "react-dom";
import TestUtils from "react-dom/test-utils";
import Dashboard from './dashboard';
describe('Dashboard', function() {
it('exists', function() {
expect(Dashboard).not.toBe(undefined);
});
it('renders arrows', function() {
var dashboard = <Dashboard />;
var renderedDashboard = TestUtils.renderIntoDocument(dashboard);
var arrowsDiv = TestUtils.findRenderedComponentWithClass('arrows');
expect(arrowsDiv).not.toBe(undefined);
});
});
【问题讨论】:
-
你检查过你的(编译的)测试的输出了吗?它们是什么格式的? UMD,AMD?因为您似乎也在使用 webpack 编译测试(至少您不排除它们)。而 webpack 默认不会编译成需要的库webpack.github.io/docs/configuration.html#output-librarytarget
标签: react jsx javascript javascript babeljs testem