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的使用更为普遍的问题,但我不能够进一步得到。
这个解决方案似乎有为我进行测试,以嘲笑的模块,但我得到了'类型错误:_howler.Howl.mockImplementation不是function' .. – choasia
Mhmm,你在记录'Howl'时得到了什么? –
'[Function:Howl] – choasia