angulargui-testingcomponent-testing

Using screen.getByText("With hard coded text") a good practice in Angular testing?


I am wondering about selecting elements by their text content using screen.getByText. My question is around the reliability of this approach. If the text value changes, the test will fail, which may not necessarily indicate a failure in the component's functionality.

For instance

it('#1 Get with hardcoded text', async () => {
    const { fixture } = await renderComponent();
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
    expect(screen.getByText('This is a warning')).toBeTruthy();
});

Would it be better to use translation keys instead? For instance:

it('#2 Get Text with Translate', async () => {
    const { fixture } = await renderComponent();
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();

    const translocoService = TestBed.inject(TranslocoService);
    const warningText = translocoService.translate('my.warning.key');
    expect(screen.getByText(warningText)).toBeTruthy();
});

Alternatively, is it better to rely on unique IDs for elements instead of using text content?

More specifically, when should we use screen.getByText()? What are the advantages and disadvantages of this approach compared to using translation keys or IDs?

I want to know the good practice to do better coding


Solution

  • This is an opinion-based question, which is probably why the downvote and the vote for closing the question. In my opinion, getting elements by text is not a good practice mainly because "text" tends to be repetitive. For example, there might be two "OK" buttons on the screen, but you want to test the one at the bottom of the page. However, the getBytext() will return the first one it finds (top-to-bottom). Finding by XPath (relative position on the DOM) or by ID are better approaches. That said, you will need to consider this when designing and coding your JavaScript code or Angular components. For example, come up with a scheme where IDs won't repeat on a page.

    Lastly, if your reply to this is "but that component's text will never change, I will ask you, "Then, why test it?" I would think that a label on a component will have a similar probability of changing than the functionality of the component.