Angular 6单元测试:afterAll \ nReferenceError中引发了错误:找不到变量:$ [英] Angular 6 Unit Tests: An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown
问题描述
在运行我的单元测试时,即使它们通过了,在所有测试运行结束时,我也会经常遇到以下错误.
When running my unit tests, from time to time, even if they pass, at the end of all the tests running, I will get the following error.
在运行PhantomJS的Jenkins CI构建上:
On my Jenkins CI build running PhantomJS:
.PhantomJS 2.1.1 (Linux 0.0.0) ERROR
{
"message": "An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown",
"str": "An error was thrown in afterAll\nReferenceError: Can't find variable: $ thrown"
}
或在Chrome上
Chrome 67.0.3396 (Windows 7 0.0.0) ERROR
{
"message": "An error was thrown in afterAll\n[object ErrorEvent] thrown",
"str": "An error was thrown in afterAll\n[object ErrorEvent] thrown"
}
我也有非常不可靠的测试,有时它们不会成功,而有时相同的测试却失败,因此我不做任何更改,所以我知道发生了一些奇怪的事情.
I also have really unreliable tests, without changing anything some times they would succeed and other times the same tests would fail, so I knew something weird was going on.
推荐答案
我的问题是由于设置测试的一种非常愚蠢的方式,我的测试中出现了竞争状况,但无论如何我还是希望在此处进行记录,因为我很难在互联网上找到我的问题的答案.
My issue was that I had a race condition in my tests due to a very stupid way of setting up my tests, but I wanted to document it here anyways because I struggled to find the answer to my issue on the internet.
我以某种方式完成的工作是声明两个beforeEach
函数来设置测试,而两个函数之一是异步的,因此我遇到了竞争状况,有时它们会出现故障并失败.
What I had somehow done was to declare two beforeEach
functions to setup my test, and one of the two was asynchronous, so I had a race condition where sometimes they ran out of order and failed.
这是我的测试的样子:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ HomeComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
因此,为解决此问题,我将所有设置整合为一个,同步beforeEach.
So to resolve this I put all the setup into one, synchronous beforeEach.
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent]
}).compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
我花了太多时间试图解决这个问题,所以我把它放在这里以拯救别人.
I wasted too much time trying to figure this out, so I'm putting it here to save someone else.
这篇关于Angular 6单元测试:afterAll \ nReferenceError中引发了错误:找不到变量:$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!