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

Jasmine测试报错NG0303:div无options属性绑定,求替代方案

解决方案

方案1:导入ECharts Angular模块到测试配置

如果你的项目使用官方封装的Angular ECharts库(比如ngx-echarts),直接在测试模块中导入对应模块,就能让Angular识别echarts指令和[options]绑定:

import { TestBed } from '@angular/core/testing';
import { NgxEchartsModule } from 'ngx-echarts';
import { TargetComponent } from './target.component'; // 替换为你的组件类名

describe('TargetComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [TargetComponent],
      imports: [NgxEchartsModule] // 导入ECharts模块
    }).compileComponents();
  });

  // 你的测试用例
});

适用场景:需要验证组件与ECharts指令的交互逻辑,属于集成测试范畴,测试环境更贴近真实运行场景。

方案2:声明模拟ECharts指令

如果只想专注于组件自身逻辑的单元测试,不想引入第三方模块增加测试复杂度,可以手动创建一个模拟指令,让测试模块识别echarts选择器和options输入属性:

import { TestBed } from '@angular/core/testing';
import { Directive, Input } from '@angular/core';
import { TargetComponent } from './target.component';

// 模拟ECharts指令,仅保留测试所需的输入属性
@Directive({
  selector: '[echarts]'
})
class MockEchartsDirective {
  @Input() options: any;
}

describe('TargetComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [TargetComponent, MockEchartsDirective], // 注册模拟指令
    }).compileComponents();
  });

  // 你的测试用例
});

适用场景:单元测试中隔离第三方依赖,聚焦组件内部逻辑,提升测试速度和稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:12:23