在Jest中的函数内模拟函数调用 [英] Mocking a function call inside a function in Jest

查看:1228
本文介绍了在Jest中的函数内模拟函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 getBookingStateObject ,它调用另一个函数 getBookingStateButtons 。反过来 getBookingStateButtons 调用另外两个函数 linkBut​​tons sendEventButtons

I have a function getBookingStateObject that calls another function getBookingStateButtons. In turn getBookingStateButtons calls two other functions linkButtons and sendEventButtons.

我正在尝试为上述场景编写测试。我的测试文件中有以下内容。

I'm trying to write tests for the above scenario. I have the following in my test file.

import {
  getBookingStateButtons,
  getBookingStateObject,
  linkButtons,
  sendEventButtons,
} from './bookingStates'

jest.mock('getBookingStateButtons', () => jest.fn())
jest.mock('linkButtons', () => jest.fn())
jest.mock('sendEventButtons', () => jest.fn())

it('calls getBookingStateButtons, linkButtons, sendEventButtons', () => {
    getBookingStateObject({ aasm_state: 'created' }, '123')
    expect(getBookingStateButtons).toHaveBeenCalledWith({
      bookingId: '123',
      events: [{ event: 'mark_requested', type: 'secondary' }],
      links: [{ to: 'edit' }],
    })
    expect(linkButtons).toHaveBeenCalledWith({
      to: 'edit',
      type: 'secondary',
    })
    expect(sendEventButtons).toHaveBeenCalledWith({
      event: 'mark_requested',
      type: 'secondary',
    })
  })

当我运行测试时我得到以下错误:
无法从'bookingStates.spec.tsx'找到模块'getBookingStateButtons'

When I run the tests I get the following error: Cannot find module 'getBookingStateButtons' from 'bookingStates.spec.tsx'

我是开玩笑的新手,我做错了什么?

I'm new to jest, What am I doing wrong?

推荐答案

问题是你试图模拟部分模块这不是 jest.mock 那样做的。它的作用是模拟整个模块,在大多数情况下你想要什么。所以在你的情况下

The problem is that you try to mock parts of module which is not what jest.mock does. What it does is to mock the whole module, what is what you want in most of the cases. So in your case

jest.mock('getBookingStateButtons', () => jest.fn())

尝试使用名称 getBookingStateButtons 模拟npm模块,所以你要安装的东西

tries to mock an npm module with the name getBookingStateButtons, so something that you want to install like this

import getBookingStateButtons from 'getBookingStateButtons'

您应该将模块视为一个黑盒子,您可以放入内容并获取内容。你不能只改变黑匣子的部分。由于我不知道'./ bookingStates'是什么,我认为它会产生一些副作用,也就是与其他导入模块的某些交互。这些是你模拟并测试它们在哪里用正确的参数调用,而不是'./ bookingStates'模块的内部。

You should think about a module as a black box where you put stuff in and get something out. You can't just change parts of the black box. As I don't know what the './bookingStates', I assume that it will have some side effects, aka some interactions with other imported modules. These are ones you shoudl mock and test that they where called with teh correct parameter, not the internals of the './bookingStates' module.

这篇关于在Jest中的函数内模拟函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆