【问题标题】:how to mock module when using jest使用 jest 时如何模拟模块
【发布时间】:2018-01-26 18:14:03
【问题描述】:

我在 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 未设置为真,因此测试失败。运行此测试时似乎不会调用模拟构造函数。

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 的使用相关的更普遍的问题,但我无法更进一步。

【问题讨论】:

    标签: javascript unit-testing vue.js jestjs


    【解决方案1】:

    您链接到的 SO 仅适用于反应组件。这是一种使用 spy on 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()
      })
    })
    

    【讨论】:

    • 这个解决方案对我来说似乎很有希望,但我得到了TypeError: _howler.Howl.mockImplementation is not a function..
    • 嗯,登录Howl会得到什么
    • [Function: Howl]
    • 模拟实现不存在
    猜你喜欢
    • 2021-01-21
    • 2018-02-19
    • 2019-08-17
    • 2021-02-04
    • 2020-02-04
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多