shane
shane

Reputation: 246

Ember controller test is not using prototype extension when called

I am trying to unit test an Ember addon that has already been written but unfortunately did not get tested at the time of its creation. I would really really like not to have to modify the existing codebase to fit the tests if possible.

Controller Code

foo() {
    return this.get('store').query('stuff', query)
        .then((data) => {
            this.setProperties({
                myList: []
            });

            data.get('content').mapBy('record').forEach((item) => {
                // fails here
                this.get('myList').pushObject(item);
            });
        });
    });
}

Test Code

beforeEach() {
    let data = Ember.Object.create({
        content: Ember.A([
            { record: { } },
            { record: { } }
        ]);
    });

    this.controller = this.subject({
        store: {
            query(property, query) {
                return new Ember.RSVP.Promise(function (resolve) {
                    resolve(data);
                });
            }
        }
    });
}

test('failing test case', function (assert) {
    this.controller.foo();
}

Error:

Uncaught TypeError: _this.get(...).pushObject is not a function

I did some research and found out that Ember extends object prototypes by default so that standard arrays ( [] ) become Ember arrays. I've checked my config/environment.js as mentioned in the how-to-disable prototype extension here and it only returns and empty object {}.

Why doesn't Ember wrap the array and allow me to use pushObject like I would expect in my tests?

PS: I've noticed that there's a package to disable prototype extension aimed at addon authors, but again I do not have this package
https://github.com/rwjblue/ember-disable-prototype-extensions

Upvotes: 1

Views: 263

Answers (1)

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7169

Using prototype extensions isn't good idea. That's the reason why ember-disable-prototype-extensions was created

No one can give you answer why Ember doesn't extend arrays in you app while you give move information about packages and your environment. But you can fix situation with explicit usage Ember.Array

instead of

   this.setProperties({
        myList: []
    });

use

   this.setProperties({
        myList: Ember.A()
    });

And that will be great cause prevent such errors in future ( on updating dependencies / packages )

Upvotes: 1

Related Questions