简体   繁体   English

测试代码为es6编译

[英]testing code transpiled for es6

I'm preparing to write some tests with Qunit for a Backbone app that is written for ES6 with babel.js applied to it so that it can run in contemporary browsers. 我准备用Qunit为一个为ES6编写的Backbone应用程序编写一些测试,并将babel.js应用于它,以便它可以在当代浏览器中运行。 To ensure that I have qunit set up properly and all the paths properly specified, I first tested an Backbone model written in ES5 and everything worked as expected. 为了确保我已正确设置qunit并正确指定所有路径,我首先测试了用ES5编写的Backbone模型,一切都按预期工作。 However, I then included bundle.js (which contains the results of my ES6 code with babel.js applied to it) into my tests/index.html , and wrote 但是,然后我将bundle.js (包含应用了babel.js的ES6代码的结果)包含在我的tests/index.html ,并写了

 test ( "Code transformed by babel.js contained in bundle.js can be tested", function(){
    expect(1);
    var es6model = new ES6Model();
    equal( es6model.get("defaultproperty"), "defaultstring", "defaultproperty should be defaultstring");
 })

and it's telling me ES6Model is not defined. 它告诉我ES6Model没有定义。

Question: is there something about code transformed by babeljs that would make it more challenging to be tested using Qunit? 问题:有什么关于babeljs转换的代码会使使用Qunit进行测试更具挑战性吗?

In addition to all the complex js that babel writes at the top of the file, the code in bundle.js looks like this 除了babel在文件顶部写的所有复杂js之外, bundle.js的代码看起来像这样

var Model = Backbone.Model;
var View = Backbone.View;
var Collection = Backbone.Collection;
var Router = Backbone.Router;
var LocalStorage = Backbone.LocalStorage;

var ES6Model = (function (Model) {
    function ES6Model() {
        _classCallCheck(this, ES6Model);

        if (Model != null) {
            Model.apply(this, arguments);
        }
    }

    _inherits(ES6Model, Model);

    _prototypeProperties(Gopher, null, {
        defaults: {
            value: function defaults() {

                return {
                    defaultproperty: "defaultstring"

                };
            },
            writable: true,
            configurable: true
        }
    });

    return ES6Model;
})(Model);

Update 更新

I include all the code created by babel.js in a file called bundle.js and include that in my index.html like I would any other js file, and it runs without issue, which is why I assumed I could test it like any other js code. 我将babel.js创建的所有代码包含在一个名为bundle.js文件中,并将其包含在我的index.html中,就像我将任何其他js文件一样,并且它运行没有问题,这就是为什么我认为我可以像任何一样测试它其他js代码。 However, it should be noted (as the commenter pointed out) that the code created by babel.js is contained in a module..this is how bundle.js begins with the model I'm trying to test coming after 但是,应该注意(正如评论者指出的那样)babel.js创建的代码包含在一个模块中。这就是bundle.js从我试图测试的模型开始的方式

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

Update 更新

I am using browserify to apply babel to the various files of my ES6 code which creates a bundle. 我正在使用browserify将babel应用于我的ES6代码的各种文件,这些文件创建了一个包。 To run the tests, I do npm run test and to compile the bundle, I try both of these (one of them uses modules --ignore ) but neither of them work 为了运行测试,我做了npm run test并编译了bundle,我尝试了这两个(其中一个使用modules --ignore )但是它们都没有工作

"scripts": { “脚本”:{

    "test": "./node_modules/karma/bin/karma start --log-level debug",
    "build-js": "browserify app/app.js app/views.js app/models.js  app/d3charts.js -t babelify > app/bundle.js",
    "t-build": "browserify app/app.js app/views.js app/models.js app/d3charts.js -t [babelify --modules ignore] > app/test/test-bundle.js"
  },

(The application is a Backbone.js app). (该应用程序是Backbone.js应用程序)。

This is my karma config file. 这是我的业力配置文件。 I don't have any further configuration (so I'm guessing my inclusion of karma-require is a waste but maybe necessary...) 我没有任何进一步的配置(所以我猜我包含karma-require是浪费但可能是必要的......)

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['qunit'],
    plugins: ['karma-qunit', 'karma-phantomjs-launcher', 'karma-requirejs'],

    files : [
      'app/test/jquery.js',     
      'app/test/d3.js',
      'app/test/json2.js',
      'app/test/underscore.js',
      'app/test/backbone.js',
      'app/backbone.localStorage.js',

      'app/test/test-bundle.js',
      'app/test/tests.js'

    ],


    reporters: ['progress'],

    // web server port
    port: 8080,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // See http://stackoverflow.com/a/27873086/1517919
    customLaunchers: {
        Chrome_sandbox: {
            base: 'Chrome',
            flags: ['--no-sandbox']
        }
    }
  });
};

For reference they way to do this with traceur is to compile the traceur-runtime.js file into the code (see https://github.com/google/traceur-compiler/issues/777 - a similar variable not defined error). 作为参考,他们使用traceur执行此操作的方法是将traceur-runtime.js文件编译到代码中(请参阅https://github.com/google/traceur-compiler/issues/777 - 未定义的类似变量错误)。

Eg 例如

traceur --out out/src/yourcode.js --script lib/traceur-runtime.js --script test/yourcode.js

(see Compiling Offline https://github.com/google/traceur-compiler/wiki/Compiling-Offline ). (请参阅编译离线https://github.com/google/traceur-compiler/wiki/Compiling-Offline )。

Import the Babel-generated module into your test before executing (recommended) 执行前将Babel生成的模块导入测试(推荐)

You'll need to include a module loader (eg SystemJS ) to handle the imports. 您需要包含一个模块加载器(例如SystemJS )来处理导入。 Babel has excellent documentation for its module system. Babel拥有出色的模块系统文档

It looks something like this: 它看起来像这样:

System.import( 'path/to/ES6Module' )
  .then( function( ES6Module ) {
    // … Run your tests on ES6Module here
  });

Note: System.import() returns a Promise , so your test suite will need to support asynchronous operations. 注意: System.import()返回一个Promise ,因此您的测试套件需要支持异步操作。


Tell Babel to skip module generation (simpler) 告诉Babel跳过模块生成(更简单)

You can tell Babel not to wrap your code in a module using the --modules ignore flag. 您可以使用--modules ignore标志告诉Babel不要将代码包装在模块中。 This allows your code to set up global variables, immediately available to your unit tests. 这允许您的代码设置全局变量,可立即用于单元测试。 Global variables are not recommended (especially in production systems), but they are simpler to apply. 不建议使用全局变量(特别是在生产系统中),但它们更易于应用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调试器在转译文件上设置断点(VS Code、Node、ES6) - Debugger setting breakpoints on transpiled file (VS Code, Node, ES6) 使用webpack和gulp的缩小的,转换的ES6代码的外部源映射 - External source maps for minified, transpiled ES6 code with webpack and gulp 在CSHTML中渲染转译的ES6 - Render Transpiled ES6 in CSHTML ES6中的JavaScript范围已转换 - JavaScript Scope in ES6 transpiled 编译的es6脚本错误 - Transpiled es6 script error Coffescript 2 输出 es6 代码。 使用webpack和coffee-loader,会自动转成ES5代码吗? - Coffescript 2 output es6 code. Using webpack and coffee-loader, will it automatically transpiled to ES5 code? ESlint:在未转译的 ES5 代码库中突出显示 ES6 代码 - ESlint: Highlighting ES6 code in an non-transpiled ES5 codebase 用于ES6课程的Mixins,用babel编译 - Mixins for ES6 classes, transpiled with babel 领先的Underscore在es6课程中出现了错误 - Leading Underscore transpiled wrong with es6 classes Babel成功地转译了ES6代码(node.js),但是当“ npm start”执行时,它会抛出“ SyntaxError:意外的令牌导入” - Babel transpiled ES6 code (node.js) successfully, but when do “npm start” it throws “SyntaxError: Unexpected token import ”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM