zsh*_*hnr 10 javascript phantomjs ember.js ecmascript-6 ember-cli
我有一个ember-cli 0.2.7使用Ember.js 1.12.0应用程序与一段代码看起来像:
controllers/cart.js
import Ember from 'ember';
export default Ember.Controller.extend({
footwearInCart: Ember.computed('model.@each.category', function() {
return this.get('model').any(product => product.get('category').includes('Footwear'));
})
});
Run Code Online (Sandbox Code Playgroud)
它遍历模型中的所有对象,如果其类别属性中包含"鞋类",则返回true.
我试图像这样测试它:
tests/unit/controllers/cart-test.js
import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
var products = [Ember.Object.create({name: 'shoe', category: 'Footwear', subTotal: 10}), Ember.Object.create({name: 'shirt', subTotal: 20})];
var model = Ember.ArrayProxy.create({
content: Ember.A(products)
});
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject();
}
});
test('footwearInCart property works', function(assert) {
this.controller.set('model', model);
assert.equal(this.controller.get('footwearInCart'), true, 'The footwearInCart function returns true if the category property of product in cart contains the word "Footwear"');
});
Run Code Online (Sandbox Code Playgroud)
代码以我运行应用程序时的方式工作,但PhantomJS显然无法识别.includes方法.(此处记录的方法是String.prototype.includes()
如何让PhantomJS识别.includes方法?
谢谢!
Ami*_*mit 10
显然PhantomJS没有正确实现ES6功能.幸运的String.prototype.includes是很容易填充.您可以选择是否要在测试套件或控制器中执行此操作.polyfill代码是:
if (!String.prototype.includes) {
String.prototype.includes = function() {'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
Run Code Online (Sandbox Code Playgroud)
要么在assert调用之前把它放好(你可能想要使用一个标志来记住你添加了polyfill并在之后删除它assert),或者在模块本身,export块之前或之后进行.
虽然选择的答案是正确的,但我认为值得注意的是,将其添加到特定测试中并不适合大多数应用程序; 我建议创建一个vendor/phantom-js-polyfills.js包含此polyfill(以及其他任何其他产品)的内容,然后在你的内部ember-cli-build.js可以有条件地加载它:
if (EmberApp.env() === 'test') {
app.import('vendor/phantom-js-polyfills.js');
}
Run Code Online (Sandbox Code Playgroud)