gpt4 book ai didi

javascript - 使用 Jest 时如何模拟模块

转载 作者:行者123 更新时间:2023-11-30 21:15:12 24 4
gpt4 key购买 nike

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

最佳答案

您链接到的 SO 仅适用于 React 组件。这是一种模拟模块的方法,可以使用 toBeHaveCalled

测试 play 函数
//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()
})
})

关于javascript - 使用 Jest 时如何模拟模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45750203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com