我可以使用Jest模拟具有特定参数的函数吗?

编程入门 行业动态 更新时间:2024-10-25 14:24:10
本文介绍了我可以使用Jest模拟具有特定参数的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用Jest来模拟一个函数,但仅当使用特定参数调用该函数时,例如:

I would like to mock a function with Jest, but only if it is called with specific arguments, for example:

function sum(x, y) { return x + y; } // mock sum(1, 1) to return 4 sum(1, 1) // returns 4 (mocked) sum(1, 2) // returns 3 (not mocked)

在Ruby的RSpec库中实现了类似的功能:

There is a similar feature implemented in the Ruby's RSpec library:

class Math def self.sum(x, y) return x + y end end allow(Math).to receive(:sum).with(1, 1).and_return(4) Math.sum(1, 1) # returns 4 (mocked) Math.sum(1, 2) # returns 3 (not mocked)

我想在测试中实现的是更好的去耦,比如说我要测试依赖于sum的函数:

What I'm trying to achieve in my tests is a better decoupling, let's say I want to test a function that relies on sum:

function sum2(x) { return sum(x, 2); } // I don't want to depend on the sum implementation in my tests, // so I would like to mock sum(1, 2) to be "anything I want", // and so be able to test: expect(sum2(1)).toBe("anything I want"); // If this test passes, I've the guarantee that sum2(x) is returning // sum(x, 2), but I don't have to know what sum(x, 2) should return

我知道有一种方法可以通过执行以下操作来实现:

I know that there is a way to implement this by doing something like:

sum = jest.fn(function (x, y) { if (x === 1 && y === 2) { return "anything I want"; } else { return sum(x, y); } }); expect(sum2(1)).toBe("anything I want");

但是如果我们有一些糖功能来简化它,那就太好了.

But it would be nice if we had some sugar function to simplify it.

听起来合理吗?我们在Jest中已经拥有此功能吗?

Does it sounds reasonable? Do we already have this feature in Jest?

感谢您的反馈.

推荐答案

我找到了我的一位同事最近写的这个库:jest-when

I found this library that a colleague of mine wrote recently: jest-when

import { when } from 'jest-when'; const fn = jest.fn(); when(fn).calledWith(1).mockReturnValue('yay!'); const result = fn(1); expect(result).toEqual('yay!');

这里是图书馆: github/timkindberg/jest-when

更多推荐

我可以使用Jest模拟具有特定参数的函数吗?

本文发布于:2023-10-31 05:50:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545198.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   函数   参数   Jest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!