.spec.ts
" extension. For example, if you have a component named "MyComponent", create a new file named "my.component.spec.ts
".HttpClient
service, you would import the HttpClientModule
.describe()
function to create the test suite. The first argument is a string that describes what is being tested, and the second argument is a function that contains the tests.it()
function to write individual tests. The first argument is a string that describes the test, and the second argument is a function that contains the test code.TestBed.createComponent()
function creates a new instance of a component for testing.expect().toEqual()
matcher checks that the actual value is equal to the expected value.MyComponent
": import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ]
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should create the component', () => {
expect(component).toBeTruthy();
});
});
In this example, we import the necessary testing dependencies, create a new test suite using the describe()
function, create a new instance of the component using the TestBed.createComponent()
function, and write a simple test using the expect().toBeTruthy()
matcher to check that the component was created successfully.