How to test String.prototype.includes in PhantomJS

大城市里の小女人 提交于 2019-12-22 04:05:30

问题


I have an ember-cli 0.2.7 using Ember.js 1.12.0 app with a piece of code that looks like:

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

It goes through all the objects in the model and returns true if their category property has 'footwear' in it.

I'm trying to test it like so:

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

The code works the way it should when I run the app, but PhantomJS apparently does not recognise the .includes method. (The method is documented here String.prototype.includes()

How can I get PhantomJS to recognize the .includes method?

Thanks!


回答1:


Apparently PhantomJS doesn't implement ES6 features properly. Luckily String.prototype.includes is quite easy to polyfill. You can choose if you want to do that in the test suite or the controller. The polyfill code is:

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

Either put it right before the assert call (you might want to use a flag to remember of you added the polyfill and remove it after the assert), or do it in the module itself, before or after the export block.




回答2:


While the selected answer is correct, I think it's worth noting that adding this into the specific test is not good enough for most apps; I'd suggest creating a vendor/phantom-js-polyfills.js that contains this polyfill (plus any others that come up down the line) and then inside your ember-cli-build.js you can conditionally load it in:

  if (EmberApp.env() === 'test') {
    app.import('vendor/phantom-js-polyfills.js');
  }



回答3:


I've used the following polyfill recently which got the job done.

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



来源:https://stackoverflow.com/questions/31360504/how-to-test-string-prototype-includes-in-phantomjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!