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

Discussão em 'Angular' iniciado por MG1616, Novembro 1, 2024.

  1. MG1616

    MG1616 Guest

    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

    Continue reading...

Compartilhe esta Página