如何设置量角器以使用requirejs导入AMD模块 [英] How to setup protractor to import AMD modules with requirejs
问题描述
我正在尝试在量角器测试中导入AMD模块(在ES5中转换为ES6的模块). 我正在使用页面对象模式.页面对象是我要导入的模块.
I'm trying to import an AMD module (ES6 module transpiled in ES5) in a protractor test. I'm using the Page Object pattern. And the Page Object is the module I'm trying to import.
这是ES6代码:
import {HelloPage} from 'HelloPage';
describe('The demo app', function () {
beforeEach(function () {
browser.get('http://localhost:3000/index.html');
});
it('should say hello',function(){
var helloPage = new HelloPage();
helloPage.setFirstName('Martin');
helloPage.submit();
// then, expect statement.
})
});
生成的ES5代码如下:
The generated ES5 code looks like this:
define(['HelloPage'], function($__0) {
"use strict";
if (!$__0 || !$__0.__esModule)
$__0 = {default: $__0};
var HelloPage = $__0.HelloPage;
describe('The demo app', function() {
beforeEach(function() {
browser.get('http://localhost:3000/index.html');
});
it('should say hello', function() {
var helloPage = new HelloPage();
helloPage.setFirstName('Martin');
helloPage.submit();
});
});
return {};
});
问题是我正在使用requirejs中的define().但是我从来没有在任何地方声明过我正在使用requirejs.所以我收到以下错误:
The problem is the fact I'm using define() from requirejs. But I never declared anywhere that I was using requirejs. So I get the following error :
Failures:
1) Exception loading: build/test/e2e/Hello.spec.js Error
Message:
ReferenceError: define is not defined
量角器conf文件是这样的:
The protractor conf file is like that :
exports.config = {
capabilities: {
'browserName': 'chrome'
},
specs: [ 'build/test/e2e/**/*.js'],
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
我应该在此配置文件中声明我正在使用requirejs执行测试吗?
Where I should declare in this configuration file that I'm using requirejs to execute tests ?
推荐答案
一种解决方案是使用amdefine,如 requirejs.org/docs/node.html#3 该解决方案的缺点是您需要在每个模块之前添加以下行:
A solution is to use amdefine as it is described in requirejs.org/docs/node.html#3 the drawback of this solution is that you need to prepend every module by the following line :
if (typeof define !== 'function') { var define = require('amdefine')(module) }
在我的特定情况下,因为我正在使用Traceur来转换ES6文件,所以我选择使用commonjs模块而不是AMD进行e2e测试.它不同于Karma执行的单元测试(在这里我可以轻松地使用AMD)的原因是,量角器测试是由Node.js而不是由浏览器执行的. 因此,我仅将e2e测试的traceur模块选项更改为此:
In my specific case, because I'm using traceur to transpile ES6 files, I chose to use commonjs module instead of AMD for e2e tests. The reason it's different from unit tests executed by Karma (where I can easily use AMD) is the fact that protractor tests are executed by Node.js and not by the browser. So, I changed the traceur modules options for e2e tests only to this:
{
"modules": "commonjs",
"script": false,
"types": true,
"annotations": true,
"memberVariables":true,
"outputLanguage": "es5"
}
这篇关于如何设置量角器以使用requirejs导入AMD模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!