遇到了这个问题,并在Internet上搜索了Fixture.detectChanges(),它在显式插入模拟数据时无法识别@Input()中的更改。有大量的线程和文档描述了安装程序,但不一定是为什么它会导致我的所有测试都无法通过。



删除fixture.detectChanges()似乎可以“解决”此错误。但是现在(根据规范)未检测到任何新的模拟数据的插入。

例子:

TestComponent.ts

import { TestComponent } from './test-component';
import { TestComponentModule } from './test-component.module';
import { Data } from './interfaces/data';

export class TestComponent {
    @Input() data: Data;

    displayData(){
        let firstName = data.first;
        let lastName = data.last;
        let fullName = firstName + ' ' + lastName;
        return fullName;
    };
}

TestComponent.spec.ts

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TestComponent } from './test-component';
import { TestComponentModule } from './test-component.module';

class DataMock {
    data: Data = getDataMock({
        first: 'Roger',
        last: 'Moore'
    });
};

describe('TestComponent', () => {
    'use strict';
    let testComponent: TestComponent;
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(async() => {
        TestBed.configureTestingModule({
        imports: [ TestComponentModule ]
        }).compileComponents();
        fixture = TestBed.createComponent(TestComponent);
        testComponent = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should render the app', () => {
        expect(TestComponent).toBeDefined();
    });

    describe('displayData()', () => {
        let dataMock = new DataMock;
        beforeEach(() => {
            testComponent.data = dataMock.data;
        });

        it('should return fullName', () => {
            expect(TestComponent.displayData()).toBe('Roger Moore');
        });
    });
});
  • 最初,类dataMock定义为const变量-在这种情况下,夹具.detectChanges()破坏了它所应用的所有测试。
  • 现在,dataMock是一个具有模拟Input()数据和Fixture的类.detectChanges()似乎可以再次使用

  • 那么,为什么要在每个规范都实例化类dataMock之前,fixture.detectChanges()才能起作用?这是原因吗?

    最佳答案

    您必须在执行compileComponents之后创建固定装置。

    beforeEach(async() => {
        TestBed.configureTestingModule({
            imports: [ TestComponentModule ]
        }).compileComponents();
    });
    
    beforeEach(() => {
        fixture = TestBed.createComponent(TestComponent);
        testComponent = fixture.componentInstance;
        fixture.detectChanges();
    });
    

    09-25 16:15