如何在使用jest时模拟模块

时间:2017-08-18 06:49:00

标签: javascript unit-testing vue.js jestjs

我在vuejs2项目中使用Jest进行单元测试,但却陷入模仿howler.js,这是我组件中导入的库。

假设我有一个名为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,但我认为这是与Jest mock API的使用相关的更一般的问题,但我无法进一步了解。

1 个答案:

答案 0 :(得分:1)

您链接的SO仅适用于反应组件。这是一种使用play函数模拟模块的方法,可以使用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()
  })
})