在Angular源代码中,单元测试文件通常与被测试的代码文件放在同一个目录下,但是命名添加“.spec”后缀。例如,如果我们有一个名为“hello.component.ts”的文件,那么我们的单元测试文件应该命名为“hello.component.spec.ts”。下面是一个例子:
假设我们有一个名为“HelloComponent”的组件类,我们可以在与组件类相同的目录中创建一个名为“hello.component.spec.ts”的单元测试文件。然后,我们可以编写像下面这样的测试:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HelloComponent } from './hello.component';
describe('HelloComponent', () => {
let component: HelloComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HelloComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HelloComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在上面的示例中,我们导入了必要的测试工具,并在一个“describe”块中定义我们的测试。我们先声明了组件和其Fixture实例的变量,并在每个测试之前实例化它们。最后,我们编写了一个简单的测试,确保组件实例已经创建。
总之,我们应该将单元测试文件与源代码文件放在同个目录中,并使用“.spec”后缀来命名测试文件。