npm install --save-dev ng-testing-library
import { async, TestModuleMetadata } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { configureEnvironment } from 'ng-testing-library';
import { FetchComponent } from './fetch.component';
import { FetchService } from './fetch.service';
describe('FetchComponent', () => {
const metaData: TestModuleMetadata = {
imports: [HttpClientModule],
declarations: [FetchComponent],
providers: [FetchService]
};
it('should create', () => {
const { component } = configureEnvironment(FetchComponent, metaData);
expect(component).toBeTruthy();
});
it('should fetch data on click', async(() => {
const { getByText, fixture, component } = configureEnvironment(
FetchComponent,
metaData
);
const spy = spyOn(component.fetchService, 'queryData');
getByText('Fetch').click();
expect(spy).toHaveBeenCalledTimes(1);
}));
});
The configureEnvironment
method returns an object with the following properties:
Test harness for interacting with the created component and its corresponding element.
The instance of the root component class.
This will search for the label that matches the given TextMatch
,
then find the element associated with that label.
This will search for all elements with a placeholder attribute and find one
that matches the given TextMatch
.
This will search for all elements that have a text node with textContent
matching the given TextMatch
.
This will return the element (normally an <img>
) that has the given alt
text. Note that it only supports elements which accept an alt
attribute:
<img>
,
<input>
,
and <area>
(intentionally excluding <applet>
as it's deprecated).
A shortcut to container.querySelector(`[data-testid="${yourId}"]`)
(and it
also accepts a TextMatch
).
Several APIs accept a TextMatch
which can be a string
, regex
or a
function
which returns true
for a match and false
for a mismatch.
See dom-testing-library#textmatch for options.