在Jest中测试对象是否为Person类实例失败,求解决方案
问题解决方法
问题根源
你使用as Person是TypeScript的类型断言,仅在编译阶段为普通对象附加Person类型的语法提示,运行时该对象本质仍是Object实例,并未通过Person构造函数创建,因此原型链中不存在Person的标识,导致toBeInstanceOf检查失败。
解决方案
1. 正确创建Person实例(推荐)
通过new Person()创建对象,确保运行时对象是Person的实例:
如果Person类无构造函数,可直接赋值属性:
import {Person} from './person'; let person = new Person(); person.firstName = 'dev'; person.lastName = 'john'; test('test if person is an instance of Person', () => { expect(person).toBeInstanceOf(Person); });
或者给Person类添加构造函数,简化实例创建:
修改Person类:
export class Person { firstName: string; lastName: string; constructor(firstName: string, lastName: string) { this.firstName = firstName; this.lastName = lastName; } }
对应的测试代码:
import {Person} from './person'; let person = new Person('dev', 'john'); test('test if person is an instance of Person', () => { expect(person).toBeInstanceOf(Person); });
2. 仅验证对象结构符合Person类型
若无需验证实例身份,仅需确保对象属性匹配Person类型结构,可使用expect.objectContaining:
import {Person} from './person'; let person = { firstName: 'dev', lastName: 'john', } as Person; test('test if person matches Person type structure', () => { expect(person).toEqual(expect.objectContaining({ firstName: expect.any(String), lastName: expect.any(String) })); });
内容的提问来源于stack exchange,提问作者adev
相关产品推荐
相关产品推荐

