【问题标题】:What is 'should create' test case in JasmineJasmine 中的“应该创建”测试用例是什么
【发布时间】:2020-05-31 15:23:43
【问题描述】:

我是使用 Jasmine 和 Karma 在 Angular 中进行单元测试的新手。我是实习生。我正在浏览一个规范文件。我想知道在这种情况下 should create 是什么意思。 TimeselectorComponent 是我要测试的组件。我从我的前辈那里拿了代码。代码是这样的:

import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { TimeselectorComponent } from './timeselector.component';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [
                ...
            ],
            providers: [...],
            declarations: [TimeselectorComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

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

    it('should create', () => {
        expect(fixture.componentInstance).toBeTruthy();
    });

    // other test cases
});

还有其他测试用例,但现在我对 'should create' 用例感到好奇。我的理解是它正在尝试测试组件是否已初始化/创建。如果我错了,请纠正我。请告诉我更多关于上面的代码。也想了解compileComponent() 方法。我检查了这个链接,但只能理解一点:

compileComponents() is asynchronous, we must use async()

我也在经历这个问题:

Error: Please call “TestBed.compileComponents” before your test

【问题讨论】:

    标签: angular unit-testing karma-jasmine


    【解决方案1】:

    每个 it 块内的字符串是一个测试用例名称。第一个测试用例是应该创建的,你将它与描述中的字符串结合起来,即 TimeSelectorComponent,它变成了 TimeSelectorComponent 应该创建的。此测试用例检查 TimeSelector 组件是否已初始化。您也可以根据您的方便或您想要编写测试用例的方式更改此字符串。

    Compilecomponents 是一种编译您在测试台中提到的所有组件的方法。执行任务需要时间,这就是为什么它是异步的,这样你的主线程就不会被阻塞,如果你想这样做,你可以并行地做一些其他的设置。这就是为什么 async 关键字是强制性的,以便在每个人都可以等到内部执行的所有异步任务完成之前。因为如果我们的组件没有准备好,测试用例就会失败。

    【讨论】:

    • 哦。哇。我也有同样的想法。但我想走在正确的轨道上。 :-)
    • 感谢您添加更多详细信息。这真的帮助了我很多。我接受这个答案。但我可能会问更多细节;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2013-08-07
    • 2018-12-14
    • 1970-01-01
    • 2021-01-04
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多