angular - Jasmine-Karma UnitTest 运行单一与运行所有
问题描述
当我在一个包中运行整个单元测试时,一些测试会失败,尽管单独运行这些测试会成功。我不知道是什么影响了一组跑步。
执行“ng test --code-coverage”命令后,Jasmine-Karma 创建以下输出。
组件 1 - 测试用例 1 = 通过 - 测试用例 2 = 通过 - 测试用例 3 = 通过
组件 2 - 测试用例 1 = 通过 / - 测试用例 2 = 失败 / - 测试用例 3 = 通过 /
例如,如果我只运行 Com2-Case2,它就会通过。
提前致谢。
这是典型的单元测试示例:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { FooterComponent } from './footer.component';
describe('FooterComponent', () => {
let comp: FooterComponent;
let fixt: ComponentFixture<FooterComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [FooterComponent],
imports: [
TranslateModule.forRoot(),
],
}).compileComponents();
}));
beforeEach(() => {
fixt = TestBed.createComponent(FooterComponent);
comp = fixt.componentInstance;
});
it('should create component === FooterComponent', () => {
expect(comp).toBeTruthy();
});
});
解决方案
我通过使用“FakeSync”和“Tick”解决了这个问题。
我意识到如果在测试用例调用中有订阅,它会影响下一个测试用例。为了克服这个问题,Tick 是解决方案。
it('should create TranslationTexts', fakeAsync(() => {
comp.ngOnInit();
tick();
expect(JSON.stringify(comp.translationTexts).length).toBeGreaterThan(0);
}));
Tick 有助于等待异步调用完成。以下资源非常有帮助。
https://codecraft.tv/courses/angular/unit-testing/asynchronous/
谢谢。
推荐阅读
- java - 如何避免 Spring Boot API 中出现 NumberFormatException
- javascript - 有没有办法从 JavaScript 的 setTimeout 循环中退出 if 语句?
- python - 尝试下载 MNIST 数据时出现 HTTP 错误
- python - 将句子中的 N 位数字替换为 N 的不同值的特定字符串
- python - 为什么函数不检查到最后一个数字?
- javascript - 对带有异常的 javascript 对象进行排序
- python - 在数值对数 X 轴上绘制垂直箱线图
- .net-core - 相同的功能有时会让我退出 (ReturnUrl)
- sql - 仅显示结果 > 2
- c - 如何使用两个指针来定义一个字符串isPalindrome?