gpt4 book ai didi

angular - 测试使用 templateUrl 的组件时出错

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:52 24 4
gpt4 key购买 nike

我可以在测试输出中看到 console.log(dummyComponentInstance); 正在被调用并评估为 undefined

此外,console.log('beforeEach done'); 永远不会被记录。

dummy.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

let dummyComponentInstance: DummyComponent;
let fixture: ComponentFixture<DummyComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [DummyComponent]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(DummyComponent);
dummyComponentInstance = fixture.componentInstance;
console.log('beforeEach done');
});
}));

it('should work', () => {
console.log(dummyComponentInstance);
expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
});
});

虚拟组件.ts

import { Component } from '@angular/core';

@Component({
selector: 'dummy',
templateUrl: './dummy.component.html'
})
export class DummyComponent {
public initialized = false;
}

运行测试后报错:

07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
Expected false to be true, 'should create DummyComponent'.
src/app/dummy.component.spec.js:21:98

最佳答案

你介意尝试一下吗?

@angular/core/testing 导入 fakeAsynctick。将 .then() 主体移动到测试用例中,并在那里使用 fakeAsync(),让我知道它是怎么回事。

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [DummyComponent]
})
.compileComponents();
}));

it('should work', fakeAsync(() => {
fixture = TestBed.createComponent(DummyComponent);
dummyComponentInstance = fixture.componentInstance;
tick();

expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
}));

希望这对你有用!

关于angular - 测试使用 templateUrl 的组件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44412753/

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