mardi 30 janvier 2018

Testing image.onload with vue-test-utils and jest

I have a vue component that loads image in a created hook and then fires "ready" event in image.onload function.

I want to test if the event is fired after image is loaded. But I can't. I changed function's code to use callback so I could test it asynchronously.

Here is my code:

created() {
  this.load();
},
methods: {
  load(callback) {
    const image = new Image();
    image.onload = () => {
      this.$emit('ready');
      callback();
    };
    image.src = this.content.imageSrc;
  },
},

And my test code:

test('@ready - emitted after image is loaded', (done) => {
  const wrapper = shallow(ViewerComponent, {
    propsData: {
      content: {
        imageSrc: 'example.png',
      },
    },
  });

  jest.mock('example.png', () => 'example.png');

  wrapper.vm.load((error) => {
    expect(wrapper.emitted().ready.length).toBe(1);
    done(error);
  });
});

But wrapper.emitted() is always empty object.

Is there any way to test event fired in image.onload function?

Aucun commentaire:

Enregistrer un commentaire