ngx-speculoos helps you write simpler, cleaner unit tests for your Angular components, based on the page object pattern. It also provides utilities to make writing Angular unit tests easier.
The library simply wraps the standard Angular ComponentFixture, and you should thus be able to understand and start using ngx-speculoos in just a few minutes if you already know how to write Angular unit tests.
If you've ever written tests like the following:
Example :ngx-speculoos allows writing the above tests in a simpler, cleaner way:
Using the CLI: ng add ngx-speculoos
Using npm: npm install --save-dev ngx-speculoos
Using yarn: yarn add --dev ngx-speculoos
MyComponentTester
class (in your my-component.spec.ts
file, typically) extending
ComponentTester<MyComponent>
, as shown above.element
, elements
, input
, select
, textarea
, button
, etc.).
See the API documentation for detailsbeforeEach
block as shown above, and enjoy.
You can also add them for all tests at once by adding the beforeEach block to the CLI-generated test.ts
file.This is the entry point for most of the functionalities of ngx-speculoos. It wraps a ComponentFixture
.
You can simply create one in your tests using
and then use it to query for sub elements, components, directives, etc. But we recommend adopting the page object pattern, in order to make your test easier to write and read, and to avoid repeating the same selectors over and over again.
You do that by writing a class that extends ComponentTester
, and provides getters (or functions)
to query for elements, components, etc.
and then in your tests, or in your beforeEach
, once you've configured the testing module, you create
an instance of your component tester.
The future of Angular is zoneless. Without ZoneJS, components have to make sure to properly notify Angular that they must be checked for changes, typically by updating signals. Instead of imperatively triggering change detections in tests, it's thus a better idea to let Angular decide if change detection must be run, in order to spot bugs where the component doesn't properly handle its state changes.
This can be done by:
When the provideAutomaticChangeDetection()
or the provideExperimentalZonelessChangeDetection()
provider is added, the ComponentTester
will run in
automatic mode. In this mode, calling detectChanges()
throws an error, because you should always
let Angular decide if change detection is necessary.
Here's an example of a test that uses this technique:
Example :In automatic mode, your test functions should be async
, and each action you do with the elements
(click()
, dispatchEvent
, etc.) should be awaited.
Most of the queries that ngx-speculoos supports are used to query for DOM elements. The queries, however,
don't actually returns native DOM elements, but wrappers around them, which are instances of TestElement
.
TestElement
has more specialized subclasses: TestHtmlElement
, TestInput
, TestSelect
, TestTextarea
, TestButton
.
Those subclasses offer helpful methods to get information or dispatch events to HTML elements, inputs, selects, etc.
Our custom matchers act on those TestElement
objects.
You can create your own subclasses of TestElement and query for them, too.
A TestElement is a wrapper around an Angular DebugElement
. So it can access the DebugElement
and the
native DOM element that it wraps. It also has an instance of the ComponentTester
which created it,
which itself wraps the Angular ComponentFixture
and thus allows detecting changes automatically after
an element has been dispatched, for example.
The first kind of query uses CSS selectors. This is simply a wrapper around Angular's DebugElement.query(By.css())
.
The second kind of query uses directive types. This is simply a wrapper around Angular's DebugElement.query(By.directive())
.
Whatever the kind of selector you choose, the methods are the same though:
element(selector)
to get the first element matching the selectorelements(selector)
to get an array of elements matching the selectorBoth of those methods will automatically return a TestInput
, or a TestSelect
, or any other TestElement
subclass that ngx-speculoos provides based on the actual type of element being matched. But if you know
in advance what the result of the query is, you can use more-specific methods, or their generic parameter.
Passing an HTML element name as selector also automatically returns the right type
input(selector)
returns a TestInput
textarea(selector)
returns a TestTextarea
select(selector)
returns a TestSelect
button(selector)
returns a TestButton
element<HtmlInputElement>(selector)
returns a TestInput
element<HtmlDivElement>(selector)
returns a TestHtmlElement<HtmlDivElement>
elements<HtmlButtonElement>(selector)
returns an Array<TestButton>
element('input')
returns a TestInput
It's often useful to get the component instance of a sub component, for example to inspect its state,
or to make one of its outputs emit something. You can do that using the component
and components
methods:
Querying using element(DatepickerDirective)
will return you a TestElement
on which the
DatepickerDirective
has been applied.
If you need to get the Datepicker
directive instance itself, then use the token()
method
(or tokens()
to get several of them)
which takes a selector (CSS or type) as first argument, and the token as second argument:
TestElement
We provide TestInput
, TestSelect
, etc. to easily inspect or interact with inputs and selects in our tests.
But what if you want the same kind of test abstraction for your own reusable components or directives, like
for example your DatepickerDirective
.
You can create your own TestElement
subclass for that. This subclass must have a constructor that
takes a ComponentTester
as first argument, and a DebugElement
as second argument.
Once you have created that class, you can use the custom()
and customs()
methods, using any selector,
to get instances of your custom `TestElement``
or, in automatic mode
Example :A query is made from the root ComponentTester
. But TestElement
themselves also support queries.
So you can query for a parent TestElement
, and then use it to perform subqueries:
We provide custom matchers, that act on TestElement
and on its more specific subclasses (TestInput
, TestSelect
, etc.).
The complete matcher list includes:
toHaveClass(className: string)
toHaveValue(value: string)
toHaveText(textContent: string)
toHaveTrimmedText(textContent: string)
toContainText(textContent: string)
toBeChecked()
toHaveSelectedIndex(index: number)
toHaveSelectedValue(value: string)
toHaveSelectedLabel(label: string)
toBeVisible()
These matchers must be installed in each test using them:
Example :or in all tests, by adding the above line of code in the test.ts
file.
TestElement
provides two methods that allow dispatching events in a simple way.
dispatchEvent(event: Event)
dispatchEventOfType(type: string)
Going through these methods automatically calls detectChanges()
on the ComponentTester
after the event has been dispatched,
so you don't need to call that yourself.
The TestElement subclasses that we provide have more specific event dispatching methods. For example
TestHtmlElement.click()
TestInput.fillWith()
for text, password, number, etc.TestInput.check()
for radios and checkboxesTestInput.uncheck()
for checkboxesTestTextarea.fillWith()
TestSelect.selectIndex()
TestSelect.selectValue()
TestSelect.selectLabel()
Creating your own TestElement subclasses is a good way to provide such custom methods to interact with your own reusable components in tests.
The library provides a stub for the ActivatedRoute
class that you typically inject in your routed components.
It mimics the behavior of the actual ActivatedRoute
, by having a snapshot and observables that emit when this
snapshot changes. And it also allows simulating navigations by imperatively changing the parameters, query parameters,
etc.
An alternative approach to injecting a stub activated route consists in using the Angular RouterTestingHarness
.
The library helps using it by providing a RoutingTester
, which is a ComponentTester
wrapping the
RouterTestingHarness
in addition to wrapping its fixture, and additionally provides helper properties.
Here's an example usage of a component displaying the value of the query parameter 'page'
and allowing
to navigate to itself with a different value for that query parameter.
Jasmine is quite verbose when creating mock objects in a typesafe way:
Example :Since most of what we mock (usually Angular services) are classes, we can actually do a bit of introspection
and create a mock that will automatically mock all the methods declared in the class. That's what our
createMock()
function does. The above code can thus be reduced to:
ngx-speculoos doesn't provide any specific support for testing with host components, but we do it a lot, simply by creating a ComponentTester for the host component rather than the component under test:
Example :Once you have that, you can access the host component using componentInstance()
,
the component under test using userComponent()
, and any element of the component under test
using the usual queries.
change
or detectChanges()
?In imperative mode, any event dispatched through a TestElement
automatically calls detectChanges()
for you.
But you still need to call change()
or detectChanges()
by yourself in the other cases:
ngOnInit()
method of your component is called. That's why creating a ComponentTester
does not automatically call
detectChanges()
. You need to do it yourself. The first call will cause the component lifecycle to start,
just as when using a ComponentFixture
directly.ActivatedRouteStub
Note that, in imperative mode, change()
calls detectChanges()
. So you can call either one of the other
when you want to trigger a change detection.
In automatic mode, any event dispatched through a TestElement
automatically calls await change()
for you.
But you still need to call await change()
by yourself in the same other cases as in the imperative mode:
TestElement
methods to act on the component element itself, rather than a sub-element?Yes. The ComponentTester
has a testElement
property, which is the TestHtmlElement
wrapping the component's element.
Please, provide feedback by filing issues, or by submitting pull requests, to the Github Project.
You can look at a minimal complete example in the demo project.
Version 13 of ngx-speculoos
introduces the automatic mode, consisting in using automatic change detection
instead of imperatively running change detections. See the Automatic change detection
section above for details.
As a result, all the methods that used to call detectChanges()
for you now return a Promise
instead of returning
void
. In imperative mode (the default), they are in fact synchronous and call detectChanges()
, just as before.
In automatic mode however, they call await change()
and should thus be awaited.
Your tests should generally keep compiling and running without changes.
But if you created custom test elements which override methods that now return a promise, and return something
other than void
, for example:
Then that won't compile anymore.
And in general, if you want your custom test element to be usable in both modes, all their method that explicitly
or indirectly called detectChanges()
should now return a promise and explicitly of indirectly call await change()
.
For example: