3
votes

I'm trying to write an integration test for a file upload component but aren't able to trigger a change event on input type file. While jQuery listener is triggered, embers change event is not fired.

I'm mocking an event with a simple object and passing this one to jQuery trigger method. It's working fine if I don't set target property of mocked event. In these case jQuery event handler and ember event are fired.

I'm mocking files with Blob objects and using that ones as target property of my mocked event. If I'm passing this one to trigger jQuery event handler is still fired but ember event is not.

This is how it looks in code.

// mock a file
let file = new Blob(['content'], { type: 'image/jpeg' });
// mock an event
let event = { type: 'change' };
// set events target
event.target = { files: [file] };
this.$('input').trigger(event);

I've created a Ember Twiddle demonstrating that this.$('input').trigger({ type: 'change' }) triggers ember change event but this.$('input').trigger({ target: { files: [file] }, type: 'change' }) does not while both is working for jQuery event handler: https://ember-twiddle.com/5189be1875c147e96d31dea41668b006?openFiles=tests.integration.components.file-input-test.js%2C

It was working in early ember versions but didn't used for a longer time so I'm not quite sure when it was broken.

Using jQuery.Event('change') instead of a plain object shows same results. So this is also not working:

jQuery.Event('change');
event.target = { files: [file] };
this.$('input').trigger(event);

Please note hat document.createEvent() or new Event() can't be used since target property of Event object is readonly.

I'm especially confused that this.$('input').on('change', () => { }) is triggered while change event of ember is not.

Update: I'm not quite sure if it's ever worked in ember. I noticed that the example I had in mind (ember-cli-file-pickers uploadFileHelper) may only work since it's not using embers change event but registers a jQuery event handler in didInsertElement hook.

1

1 Answers

0
votes

You can use the Ember test helper triggerEvent.

I look like this

import { triggerEvent } from '@ember/test-helpers'
...
triggerEvent(selector, eventName, options)

I've implemented a file upload event like this triggerEvent(selector, 'change', files)

Here is the doc: https://github.com/emberjs/ember-test-helpers/blob/master/API.md#triggerevent