如何在 PhantomJS 中测试 String.prototype.includes

How to test String.prototype.includes in PhantomJS

我有一个 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'));
    })
});

它遍历模型中的所有对象,如果它们的类别 属性 中有 'footwear',则 returns 为真。

我正在尝试这样测试它:

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"');
});

当我 运行 应用程序时,代码按应有的方式工作,但 PhantomJS 显然无法识别 .includes 方法。 (该方法记录在此处 String.prototype.includes()

如何让 PhantomJS 识别 .includes 方法?

谢谢!

显然 PhantomJS 没有正确实现 ES6 特性。幸运的是 String.prototype.includes 很容易填充。您可以选择是否要在测试套件或控制器中执行此操作。 polyfill代码是:

if (!String.prototype.includes) {
  String.prototype.includes = function() {'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}

要么把它放在 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');
  }

我最近使用了以下 polyfill,它完成了工作。

https://www.npmjs.com/package/phantomjs-polyfill-string-includes