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

使用expect库测试时遇TypeError: expect(...).toBeA is not a function错误求助

解决TypeError: expect(...).toBeA is not a function错误

这个问题是因为你当前使用的expect库版本已经更新,旧的toBeA和toInclude方法已经被废弃或重命名了,下面是具体的修复方案:

1. 替换废弃的断言方法

  • 对于检查createdAt的数字类型,把expect(message.createdAt).toBeA('number');替换为基于typeof的断言(针对原始类型判断更准确):
    expect(typeof message.createdAt).toBe('number');
    
  • 对于检查对象是否包含指定键值对,把expect(message).toInclude({from, text});替换为toMatchObject方法:
    expect(message).toMatchObject({from, text});
    

2. 修改后的完整测试代码

var expect = require('expect');
var {generateMessage} = require('./message');

describe('generateMessage', () => {
  it('should generate correct message object', () => {
    var from = 'Jen';
    var text = 'Some message';
    var message = generateMessage(from, text);
    
    expect(typeof message.createdAt).toBe('number');
    expect(message).toMatchObject({from, text});
  });
});

可选方案(不推荐)

如果你执意要沿用旧版断言语法,可以安装不再维护的旧版本expect:

npm install expect@1.20.2 --save-dev

但更建议使用新版语法,旧版本可能存在安全隐患且不会再收到更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:39:03