所以我试图运行" ng test"在我的Angular 4 Angular CLI上。我有很多问题,例如如果测试失败,UI没有加载任何有用的消息,但幸运的是控制台正常工作。无论如何,这个错误正在发生,说我没有给MatSnackBar提供规范中的提供程序,但是当我这样做时,我得到了一个不同的错误。
Chrome 66.0.3359 (Linux 0.0.0) BranchNameCellComponent should create FAILED
Error: No provider for MatSnackBar!
将MatSnackBar包含为导入
时出错Chrome 66.0.3359 (Linux 0.0.0) BranchNameCellComponent should create FAILED
Failed: Unexpected value 'MatSnackBar' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
在我的组件代码中,我导入MatSnackBar并在构造函数中调用它。它工作正常。
import { MatSnackBar } from '@angular/material';
....
constructor(private httpClient: HttpClient, private fb: FormBuilder, public snackBar: MatSnackBar) { }
但是在规范中,我试着这样做无济于事。
import { MatSnackBar } from '@angular/material';
....
describe('BranchNameCellComponent', () => {
let component: BranchNameCellComponent;
let fixture: ComponentFixture<BranchNameCellComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BranchNameCellComponent ],
imports: [ HttpClientTestingModule, ReactiveFormsModule, MatSnackBar ],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
it('should create', () => {
fixture = TestBed.createComponent(BranchNameCellComponent);
component = fixture.componentInstance;
expect(component).toBeTruthy();
});
});
在导入像Diego建议的模块后,我现在在同一个测试中得到超时错误
08 06 2018 16:14:52.839:WARN [Chrome 66.0.3359 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
Chrome 66.0.3359 (Linux 0.0.0) ERROR
Chrome 66.0.3359 (Linux 0.0.0) ERROR
Disconnected, because no message in 10000 ms.
Chrome 66.0.3359 (Linux 0.0.0): Executed 16 of 56 DISCONNECTED (11.204 secs / 1.241 secs)
Chrome 66.0.3359 (Linux 0.0.0) ERROR
Chrome 66.0.3359 (Linux 0.0.0): Executed 16 of 56 DISCONNECTED (11.204 secs / 1.241 secs)
答案 0 :(得分:7)
您应该导入模块而不是组件。
import { MatSnackBar, MatSnackBarModule } from '@angular/material';
....
describe('BranchNameCellComponent', () => {
let component: BranchNameCellComponent;
let fixture: ComponentFixture<BranchNameCellComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BranchNameCellComponent ],
imports: [ HttpClientTestingModule, ReactiveFormsModule, MatSnackBarModule ],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
it('should create', () => {
fixture = TestBed.createComponent(BranchNameCellComponent);
component = fixture.componentInstance;
expect(component).toBeTruthy();
});
});
对于与超时相关的问题,请尝试将此添加到您的karma配置中:
captureTimeout: 210000,
browserDisconnectTolerance: 3,
browserDisconnectTimeout : 210000,
browserNoActivityTimeout : 210000,
答案 1 :(得分:2)
在我的角度应用程序中,当我导航到某个延迟加载的模块时,我遇到了此错误。该模块正在导入MatSnackBarModule
,但我也需要在MatSnackBarModule
文件中导入app.module.ts
答案 2 :(得分:2)
这最近发生在我身上,我决定这样做::
包含文件 aap.module.ts
import { MatSnackBarModule } from '@angular/material/snack-bar';
...
...
imports: [
...
MatSnackBarModule
]
...
关于文件组件或服务:
import { MatSnackBar } from '@angular/material/snack-bar';
...
...
constructor(private snackBar: MatSnackBar) { }
...