代码之家  ›  专栏  ›  技术社区  ›  Codehan25

(角度单元测试)如何在Jasmin中模拟输入属性?

  •  0
  • Codehan25  · 技术社区  · 5 年前

    TypeError:无法读取未定义的属性“data”

    我的HTML模板如下所示

    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <plot [data]="graph.data" [layout]="graph.layout"></plot>
        </div>
      </div>
    </div>
    

    我的组件如下:

    ...
    export class ChartComponent implements OnInit {
    
      @Input() currentChart: Chart;
    
      currentLocationData: any;
    
      public graph = {
        data: [
          {
            type: 'bar',
            x: [1, 2, 3],
            y: [10, 20, 30],
          }
        ],
        layout: {
          title: 'A simple chart',
        },
        config: {
          scrollZoom: true
        }
      };
    
      ...
    }
    

    describe('ChartComponent', () => {
    
      let component: ChartComponent;
      let fixture: ComponentFixture<ChartComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ChartComponent],
          imports: [
            // My imports
          ]
        })
          .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(ChartComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });
    

    我尝试了不同的方法来模拟数据属性和 currentChart @Input .

    0 回复  |  直到 5 年前
        1
  •  1
  •   Wesley Trantham    5 年前

    input属性的工作方式与任何变量一样。在beforeach中,可以将其设置为值

    beforeEach(() => {
      fixture = TestBed.createComponent(ExplorerChartViewComponent);
      component = fixture.componentInstance;
      component.currentChart = someChart; // set input before first detectChanges
      fixture.detectChanges();
    });
    

    你可以阅读更多关于这个 here . 我更喜欢 this approach .

    @Component({
      selector: 'app-testhost-chart',
      template: `<app-chart [currentChart]=chart></app-chart>`, // or whatever your Chart Component Selector is
    })
    export class TestHostComponent {
      chart = new Chart();
    }
    

     declarations: [ChartComponent, TestHostComponent ],
    ...
    beforeEach(() => {
      fixture = TestBed.createComponent(TestHostComponent );
      component = fixture.debugElement.children[0].componentInstance;
      fixture.detectChanges();
    });
    

    不过,我想我看到了另外两个问题。尤其是在分配图形时

    1. 你把 declarations: [ChartComponent], 但是创造 fixture = TestBed.createComponent(ExplorerChartViewComponent); 我想应该是的 TestBed.createComponent(ChartComponent)
    2. 你的html有 <plot [data]="graph.data" [layout]="graph.layout"></plot> 表示未声明的打印组件。您需要为plot声明一个组件。我建议您做一些与TestHostComponent非常相似的事情,但是它与真正的PlotComponent具有所有相同的公共属性,这样您就不会将PlotComponent的真正功能和依赖性引入到ChartComponent的单元测试中。