我正在使用Angular2(rc4)和Webpack在Electron应用上工作。单元测试与Karma一起运行。
我有一个与电子过程通信的服务,它以这种方式包含它:
import { remote } from 'electron';
@Injectable()
export class SettingsService {
main = remote.require('./main.js');
settings: any;
constructor() {
this.settings = this.main.getSettings();
}
}
当我想为此文件编写单元测试时,karma运行器会抛出此错误:
Error: Cannot find module "electron"
at webpack:///src/app/services/settings.service.ts:9:0 <- spec-bundle.js:88524
如果我添加目标:&#39;电子渲染器&#39;到webpack.test.js配置文件,错误更改为:
ReferenceError: Can't find variable: require
at webpack:/external%20%22electron%22:1:0 <- spec-bundle.js:83860
这是我的webpack.test.js文件:
const helpers = require('./helpers');
module.exports = {
devtool: 'inline-source-map',
resolve: {
extensions: ['', '.ts', '.js']
},
module: {
loaders: [
{
test: /\.ts$/,
loader: 'ts'
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'null'
},
{
test: /\.css$/,
loader: 'null'
}
],
postLoaders: [
{
test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader',
include: helpers.root('src'),
exclude: [
/\.(e2e|spec)\.ts$/,
/node_modules/
]
}
]
},
target:'electron-renderer'
}
问题是:如何在与Electron过程通信的Angular2组件上运行单元测试。
答案 0 :(得分:0)
解决方案是使用业力电子。
应该将karma.conf.js更改为使用电子作为浏览器:
var webpackConfig = require('./webpack.test');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [{ pattern: './spec-bundle.js', watched: false }],
preprocessors: { './spec-bundle.js': ['electron', 'coverage', 'webpack', 'sourcemap'] },
webpack: webpackConfig,
coverageReporter: {
dir: '../coverage/',
reporters: [
{
type: 'text-summary',
type: 'json',
type: 'html',
}
]
},
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
reporters: ['spec', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Electron'],
singleRun: true,
client: {
useIframe: false
}
};
config.set(_config);
};
然而,这仍然会引发错误:
Uncaught ReferenceError: exports is not defined
at <appath>/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:32
这已经在jasmine-core中解决了,但还没有在jasmine-npm中解决(参见:https://github.com/jasmine/jasmine/issues/1144
解决方法直到发布新的npm版本的jasmine-core是使用直接github链接而不是package.json中的npm包版本:
"devDependencies": {
....
"jasmine-core": "https://github.com/jasmine/jasmine.git",
....
}