javascript - how to mock module when using jest -


i'm using jest unit test in vuejs2 project got stuck in mocking howler.js, library imported in component.

suppose have component named player.vue

<template>   <div class="player">     <button class="player-button" @click="play">player</button>   </div> </template>  <script> import { howl } 'howler';  export default {   name: 'audioplayer',   methods: {     play() {       console.log('player button clicked');       new howl({         src: [ 'whatever.wav' ],       }).play();     }   } } </script> 

then have test file named player.spec.js. test code written based on answer here, test failed since called wasn't set true. seems mocked constructor won't called when running test.

import player './player'; import vue 'vue';  describe('player', () => {   let called = false;    jest.mock('howler', () => ({     howl({ src }) {       this.play = () => {         called = true;         console.log(`playing ${src[0]} now`);       };     },   }));    test('should work', () => {     const constructor = vue.extend(player);     const vm = new constructor().$mount();     vm.$el.queryselector('.player-button').click();     expect(called).tobetruthy(); // => fail   }) }) 

though i'm using vuejs here, considered more general question related usage of jest's mock api, i'm not able further.

the linked works react components. here way mock module spy on play function can tested tobehavecalled

//import mocked module import { howl } 'howler';  // mock module returns object spy jest.mock('howler', () => ({howl: jest.fn()});  const howlmock ={play: jest.fn()} // set actual implementation of spy returns object play function howl.mockimplementation(()=> howlmock)  describe('player', () => {   test('should work', () => {     const constructor = vue.extend(player);     const vm = new constructor().$mount();     vm.$el.queryselector('.player-button').click();     expect(howl).tobehavecalledwith({src:[ 'whatever.wav' ]})     expect(howlmock.play).tobehavecalled()   }) }) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -