Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在使用jest时模拟模块_Javascript_Unit Testing_Vue.js_Jestjs - Fatal编程技术网

Javascript 如何在使用jest时模拟模块

Javascript 如何在使用jest时模拟模块,javascript,unit-testing,vue.js,jestjs,Javascript,Unit Testing,Vue.js,Jestjs,我在一个vuejs2项目中使用Jest进行单元测试,但被困在mocking中,mocking是一个导入到我的组件中的库 假设我有一个名为Player.vue的组件 虽然我在这里使用的是Vuejs,但我认为这是一个与Jest的模拟API的使用有关的更一般的问题,但我无法进一步说明。因此您链接到的仅适用于react组件。下面是一种使用spy on play函数模拟模块的方法,该函数可以通过toBeHaveCalled进行测试 这个解决方案对我来说似乎很有希望,但我得到了TypeError:_howl

我在一个vuejs2项目中使用Jest进行单元测试,但被困在mocking中,mocking是一个导入到我的组件中的库

假设我有一个名为Player.vue的组件


虽然我在这里使用的是Vuejs,但我认为这是一个与Jest的模拟API的使用有关的更一般的问题,但我无法进一步说明。

因此您链接到的仅适用于react组件。下面是一种使用spy on play函数模拟模块的方法,该函数可以通过toBeHaveCalled进行测试


这个解决方案对我来说似乎很有希望,但我得到了TypeError:_howler.Howl.mockImplementation不是一个函数..Mhmm,当记录Howl[function:Howl]mockImplementation不存在时,你会得到什么
<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>
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
  })
})
//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()
  })
})