Search code examples
angularangular-materialjasmine

Testing that element is NOT present with Angular harness


I wrote a harness to test my angular-material based dialog and in one of my test cases I need to check that a certain checkbox is NOT rendered. Querying for this checkbox throws an error because it is not found. How can I assert the existence instead of erroring?

Harness:

class ModalHarness extends ComponentHarness {
    static hostSelector = 'modal';

    getCancelBtn = this.locatorFor('.modal-cancel-button button');
    getConfirmBtn = this.locatorFor('.modal-action-button button');
    getCheckbox = this.locatorFor('#tax-country-no-tin');

    async submitDialog() {
        const confirmBtn = await this.getConfirmBtn();
        await confirmBtn.dispatchEvent('click');
    }

    async cancelDialog() {
        const cancelBtn = await this.getCancelBtn();
        await cancelBtn.dispatchEvent('click');
    }

    async getHarnessLoaderForContent(): Promise<HarnessLoader> {
        const rootLocator = this.documentRootLocatorFactory();
        const foo = await rootLocator.harnessLoaderFor('modal');
        return foo;
    }
}

Test:

it('should not display tax number optional checkbox', async function (this: SharedTestData) {
    this.create(); // lots of mocking

    const harness = await harnessLoader.getHarness(ModalHarness);
    const checkbox = await harness.getCheckbox();

    expect(checkbox).toBeFalsy();
});

Querying the checkbox throws following error for this test case:

Error: Failed to find element matching one of the following queries:
(TestElement for element matching selector: "#tax-country-no-tin")

So, how can I safely test an element is NOT present?

Thanks in advance for any help!


Solution

  • I should have researched more. Re-reading the documentation I found that the harness API offers an optional locator: locatorForOptional. More here. This optional locator will return null instead of throwing an error.

    In my example, the fix is to replace the locator for the checkbox:

    getCheckbox = this.locatorForOptional('#tax-country-no-tin');
    

    Et voilá! I can assert that the element is not present :)