【问题标题】:Split Angular component unit test containing async拆分包含异步的 Angular 组件单元测试
【发布时间】:2017-10-27 10:27:55
【问题描述】:

我有一个组件,它通过服务从服务器加载一些数据,并显示出来。

我已经为组件编写了以下测试(有效):

...
it('Should contains data after loading', async(() => {
    fixture.whenStable().then(() => {
        fixture.detectChanges();
        expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
        expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
        element.querySelectorAll('ul > li').forEach((li, index) => {
            expect(li.textContent.trim()).toBe(expectedListItem[index]);
        });
    });
}));

是否有可能将所有期望拆分为单独的 it 测试?

我想要这样的东西:

...
describe('Component contains data after loading', async(() => {
    fixture.whenStable().then(() => {
        fixture.detectChanges();

        it('Should contain title', () => {
            expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
        });

        it('Should contain paragraph', () => {
            expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
        });

        it('Should contain list', () => {
            element.querySelectorAll('ul > li').forEach((li, index) => {
                expect(li.textContent.trim()).toBe(expectedListItem[index]);
            });
        });
    });
}));

但我在describe 行中收到错误Argument of type '(done: any) => any' is not assignable to parameter of type '() => void'

编辑:

添加了TestBed 设置。

beforeEach(async(() => {
    serviceMock = prepareServiceMock();
    TestBed.configureTestingModule({
        declarations: [
            TestComponent
        ],
        providers: [
            { provide: TestService, useValue: serviceMock }
        ]
    }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
});

【问题讨论】:

  • 您的TestBed 配置在哪里?

标签: angular unit-testing typescript jasmine angular-components


【解决方案1】:

每个测试规范都将单独执行。所以你可以做的是每次在新规范开始时调用fixture.detectChanges();

it('Should contain title', async(() => {
  fixture.detectChanges();
  fixture.whenStable().then(() => {
  expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
 }
})); 

it('Should contain paragraph', async(() => {
      fixture.detectChanges();
      fixture.whenStable().then(() => {
      expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
    }
})); 

确保每次都创建新组件。

beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
});

【讨论】:

  • 所以不可能将whenStable().then代码提取到一个单独的公共块中?
猜你喜欢
  • 2020-08-02
  • 2017-11-19
  • 2017-04-07
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
  • 2012-07-15
  • 2017-12-11
  • 2021-01-05
相关资源
最近更新 更多