component=new componentClass()与component=fixture.createInstance:Angular2

component=new componentClass()与component=fixture.createInstance:Angular2,angular,angular2-testing,Angular,Angular2 Testing,根据Angular2测试文档,对于测试组件,我们应该创建如下对象: component = fixture.createInstance; component = new componentClass(); //traditional way of creating objects by calling class constructor 但是对于单元测试,比如服务,据说创建了这样一个实例: component = fixture.createInstance; component = n

根据Angular2测试文档,对于测试组件,我们应该创建如下对象:

component = fixture.createInstance;
component = new componentClass(); //traditional way of creating objects by calling class constructor
但是对于单元测试,比如服务,据说创建了这样一个实例:

component = fixture.createInstance;
component = new componentClass(); //traditional way of creating objects by calling class constructor

我不太清楚这两种创建实例的方法之间到底有什么区别。另外,我注意到使用这两种方法时的可访问性差异。有人清楚这两者之间的区别吗?

当您只想测试类的内部行为时,可以使用独立测试。比如说

class MyComponent {
  doSomething(): string {}
}

let component = new MyComponent();
expect(component.doSomething()).toBe('Hello World');
这里只测试
doSomething
方法的行为。就这样

使用独立测试,您无法测试DOM交互,因为模板从未编译过。为此,我们应该让Angular创建组件。然后组件将经历它在实际应用程序中所经历的实际生命周期

@Component({
  template: `<h1>{{ message }}</h1>
})
class MyComponent {
  message = 'Hello World'
}

let fixture = TestBed.createComponent(MyComponent);
fixture.component.message = 'new message';
fixture.detectedChanges();
expect(fixture.debugElement.query(By.css('h1')).nativeElement.textContent)
  .toBe('new message');
@组件({
模板:`{message}}
})
类MyComponent{
message='Hello World'
}
让fixture=TestBed.createComponent(MyComponent);
fixture.component.message='新消息';
fixture.detectedChanges();
expect(fixture.debugElement.query(By.css('h1')).nativeElement.textContent)
.toBe(“新消息”);

你不能在一个单独的测试中做到这一点。

这是一个完美的答案!谢谢!