You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jasmine中检查函数是否被传入真值(非undefined等)调用?

在Jasmine中检查函数是否被传入真值调用

当然可以实现这个需求!Jasmine并没有限制你必须用精确值匹配,我们有几种灵活的方式来检查函数是否被传入了真值(非null、undefined、false、0、''或NaN这类值)调用。下面分享两种常用的方案:

方案一:手动获取调用参数并断言

如果你的spy只被调用一次,或者你只关心最近一次的调用情况,可以直接通过spy的calls属性拿到调用参数,再用toBeTruthy()做断言,简单直接:

// 创建一个spy函数
const targetFunc = jasmine.createSpy('targetFunc');

// 模拟调用函数,传入一个真值
targetFunc('我是真值');

// 获取最近一次调用的第一个参数,断言它是真值
expect(targetFunc.calls.mostRecent().args[0]).toBeTruthy();

// 如果要检查所有调用的参数都是真值,还可以遍历所有调用记录
targetFunc(true);
targetFunc(123);

targetFunc.calls.allArgs().forEach(args => {
  expect(args[0]).toBeTruthy();
});

方案二:自定义匹配器(更优雅、可复用)

如果你需要在多个测试用例里做这种检查,自定义一个匹配器会让代码更简洁易读。我们可以封装一个toHaveBeenCalledWithTruthy匹配器:

// 在测试初始化时注册自定义匹配器(比如放在beforeEach里)
beforeEach(() => {
  jasmine.addMatchers({
    toHaveBeenCalledWithTruthy: function(util) {
      return {
        compare: function(spy) {
          const result = {};
          
          // 先检查spy有没有被调用过
          if (spy.calls.count() === 0) {
            result.pass = false;
            result.message = '预期 spy 被传入真值调用,但它从未被调用过';
            return result;
          }
          
          // 检查所有调用的第一个参数是否都是真值
          const allArgsAreTruthy = spy.calls.allArgs().every(args => util.isTruthy(args[0]));
          
          result.pass = allArgsAreTruthy;
          if (result.pass) {
            result.message = '预期 spy 没有被传入真值调用,但它确实被这样调用了';
          } else {
            result.message = '预期 spy 被传入真值调用,但部分调用传入了假值';
          }
          return result;
        }
      };
    }
  });
});

// 使用自定义匹配器
const targetFunc = jasmine.createSpy('targetFunc');
targetFunc('有效的真值');
expect(targetFunc).toHaveBeenCalledWithTruthy();

// 如果传入假值,断言会失败
targetFunc(null);
expect(targetFunc).toHaveBeenCalledWithTruthy(); // 这会触发断言错误

小提示

如果只需要检查某一次特定的调用(比如第一次调用),可以把自定义匹配器里的allArgs()改成first().args或者argsFor(index)来调整检查逻辑。

内容的提问来源于stack exchange,提问作者Green Mint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:36:41