Angular 6与Jest测试报错:TypeError: testing.TestBed.inject is not a function
解决Angular测试报错:
TypeError: testing.TestBed.inject is not a function 问题场景
在Angular项目中使用Angular Testing Library渲染组件时测试失败,抛出错误:TypeError: testing.TestBed.inject is not a function。
组件代码
import { Component, Input } from "@angular/core"; @Component({ selector: 'counter', template: ` <button (click)="decrement()">-</button> <span data-testid="count">Current Count: {{ counter }}</span> <button (click)="increment()">+</button> `, }) export class CounterComponent { @Input() counter = 0 increment() { this.counter += 1 } decrement() { this.counter -= 1 } }
测试代码
import {render, screen } from '@testing-library/angular' import {CounterComponent} from './prueba.component' describe('Counter', () => { test('should render counter', async () => { await render(CounterComponent, { componentProperties: {counter: 5}, }) expect(screen.getByText('Current Count: 5')).toBeTruthy(); }) })
报错原因
这个错误的核心是Angular版本与Angular Testing Library版本不兼容:
TestBed.inject是Angular 9及以上版本才引入的API,如果项目使用的Angular版本低于9,Testing Library调用该API时就会报错。- 若Angular版本符合要求,但Testing Library版本过高/过低,也会出现依赖API不匹配的问题。
解决方案
- 升级Angular版本(若低于9)
执行命令升级核心包:
ng update @angular/core @angular/cli
按照终端提示完成升级,确保版本达到9及以上。
- 匹配Testing Library与Angular版本
查看package.json中@testing-library/angular的版本,对照官方版本要求调整(例如v12+对应Angular 12+),执行安装命令适配版本:
npm install @testing-library/angular@[对应版本号]
- 检查测试配置
确认tsconfig.spec.json中没有错误的路径映射,确保@angular/core/testing可以正常导入,避免因配置问题导致API无法识别。
内容的提问来源于stack exchange,提问作者Felipe Ignacio Moyano carreño
相关产品推荐
相关产品推荐

