2017-08-18 43 views
1

我在vuejs2项目中使用Jest进行单元测试,但卡在模拟howler.js,一个导入到我的组件中的库。如何在使用jest时模拟模块

假设我有一个名叫成分Player.vue

<template> 
    <div class="player"> 
    <button class="player-button" @click="play">Player</button> 
    </div> 
</template> 

<script> 
import { Howl } from 'howler'; 

export default { 
    name: 'audioplayer', 
    methods: { 
    play() { 
     console.log('player button clicked'); 
     new Howl({ 
     src: [ 'whatever.wav' ], 
     }).play(); 
    } 
    } 
} 
</script> 

然后我有它的测试文件命名为Player.spec.js。测试代码是根据回答here编写的,但测试失败,因为called未设置为true。运行此测试时似乎不会调用模拟的构造函数。

import Player from './Player'; 
import Vue from '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(); // => will fail 
    }) 
}) 

虽然我在这里使用Vuejs,我认为这是关系到玩笑的mock API的使用更为普遍的问题,但我不能够进一步得到。

回答

1

您链接到的SO只适用于反应组件。这是一种方式与播放功能的间谍可以与toBeHaveCalled

//import the mocked module 
import { Howl } from 'howler'; 
// mock the module so it returns an object with the spy 
jest.mock('howler',() => ({Howl: jest.fn()}); 

const HowlMock ={play: jest.fn()} 
// set the actual implementation of the spy so it returns the object with the 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() 
    }) 
}) 
+0

这个解决方案似乎有为我进行测试,以嘲笑的模块,但我得到了'类型错误:_howler.Howl.mockImplementation不是function' .. – choasia

+0

Mhmm,你在记录'Howl'时得到了什么? –

+0

'[Function:Howl] – choasia

相关问题