gpt4 book ai didi

unit-testing - Angular 2 测试 - 无法创建组件

转载 作者:行者123 更新时间:2023-11-28 20:28:32 25 4
gpt4 key购买 nike

我的应用程序有很多模块,包含许多组件和服务以及其他 Angular2 内容。

现在我正在尝试使用 TestBed 方法通过 jasmine + karma 创建单元测试。

我在展示概念证明时遇到了错误。我已经为我的其中一个组件创建了一个测试,它看起来像这样:

let myCompServiceStub = {} as MyComponentService;
let routerStub = {} as Router;
let globalServiceStub = {} as MyGlobalService;

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

beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [MyModule],
providers: [
{ provide: MyComponentService, useValue: myCompServiceStub },
{ provide: Router, useValue: routerStub },
{ provide: MyGlobalService, useValue: globalServiceStub }
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(MyComponent);
// component = fixture.componentInstance;
});
}));


it('test it', () => {
expect(true).toBe(true);
});
});

MyModule 有一堆其他模块的导入(大部分是我的,但也有 CommonModule, MaterializeModule, FormsModule 模块来自 Angular 和 Materialize),它们定义一些全局组件。它还在提供程序中有一个 MyComponentService。导入的自定义模块没有提供服务。

MyGlobalServiceAppComponent中提供,是主要组件。

当我尝试运行测试时,出现错误:

PhantomJS 2.1.1 (Windows 8 0.0.0) MyComponent test it FAILED
invokeTask@karma-shim.js:8833:41
onInvokeTask@karma-shim.js:10715:50
invokeTask@karma-shim.js:8832:53
runTask@karma-shim.js:8709:58
drainMicroTaskQueue@karma-shim.js:8976:43
run@karma-shim.js:4098:31
karma-shim.js:4111:33
flush@karma-shim.js:4466:13
resolvePromise@karma-shim.js:9045:79
karma-shim.js:9081:32

而且我真的坚持下去,没有好的想法我做错了什么?

我的测试依赖如下:

"@angular/common": "~2.3.0",
"@angular/compiler": "~2.3.0",
"@angular/compiler-cli": "^2.3.1",
"@angular/core": "~2.3.0",
"@angular/forms": "~2.3.0",
"@angular/http": "~2.3.0",
"@angular/platform-browser": "~2.3.0",
"@angular/platform-browser-dynamic": "~2.3.0",
"@angular/platform-server": "^2.3.1",
"@angular/router": "~3.3.0",
"angular2-materialize": "6.3.0",
"karma": "1.1.2",
"karma-chrome-launcher": "^1.0.1",
"karma-coverage": "^1.0.0",
"karma-jasmine": "^1.0.2",
"karma-phantomjs-launcher": "^1.0.0",
"karma-remap-istanbul": "0.1.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "1.7.0",
"@types/jasmine": "^2.5.36",
"jasmine-core": "^2.3.4",
"jasmine-spec-reporter": "^2.4.0",

最佳答案

确保你确实通过

导入了你的组件(看不到你是否导入了)
import { MyComponent } from './MyComponent.component';
import { FormsModule } from '@angular/forms';

同样在您的 TestBed.configureTestingModule 中将您的组件设置为声明

    TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports:[FormsModule ],
providers:[]
})
.compileComponents()
}));

附注我还在我的所有测试组件上导入了 FormsModule。

关于unit-testing - Angular 2 测试 - 无法创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com