“ReferenceError: System is not defined” when using protractor with Angular2 and .ts specs

旧城冷巷雨未停 提交于 2019-11-30 20:32:30

When you run an e2e test through Protractor, there are actually 2 environments:

  • The first is the environment being tested
    • it runs in a browser,
    • said browser is controlled through the "Selenium Webdriver" automation system,
    • it loads and execute your whole application as an end-used browser would, including loading the index.html file.
  • The second is the environment running the tests themselves
    • In runs in as a local node.js application,
    • It uses protractor, which runs Jasmine, which runs the e2e test files
    • It controls the browser through Selenium

Even if you load libraries in your index.html file, the your e2e-spec file won't have access to them. That includes systemjs. This is an issue when the Typescript compiler uses "module": "system"

How to fix it?

One solution is to configure your build process so that the e2e-spec files are compiled with the "module": "commonjs" option. If you want to be able to import files from your web application into the test spec, you would have to compile the whole application twice (though I am not sure there are much use cases where it makes sense to do so).

For example, using gulp

const gulpTypings = require('gulp-typings')
const sourcemaps = require('gulp-sourcemaps')
const ts = require('gulp-typescript')

const tsProject = ts.createProject('tsconfig.json')
const tsProjectE2E = ts.createProject('tsconfig-e2e.json')

const tsFiles = [
  'typings/index.d.ts',
  'app/**/*.ts',
  '!**/*.e2e-spec.ts',
  '!node_modules/**/*'
]

const tsFilesE2E = [
  'typings/index.d.ts',
  'app/**/*.e2e-spec.ts',
  'app/**/*.ts', // You should not need that unless you use your app files in your tests
  '!node_modules/**/*'
]

gulp.task('typings', () => gulp
  .src('./typings.json')
  .pipe(gulpTypings())
)

gulp.task('ts', ['typings'], () => gulp
  .src(tsFiles)
  .pipe(sourcemaps.init())
  .pipe(ts(tsProject))
  .js
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('app'))
)

gulp.task('ts-e2e', ['typings'], () => gulp
  .src(tsFilesE2E)
  .pipe(sourcemaps.init())
  .pipe(ts(tsProjectE2E))
  .js
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('e2e')) // Note that your compiled tests files are put in the e2e/ folder now
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!