Here is my testing code with testing-library
with angular
. Here I am using title
variable for regexp
.
import { render, screen } from '@testing-library/angular';
import '@testing-library/jest-dom';
import { AppComponent } from './app.component';
describe('App component', () => {
it('app should render', async () => {
const title = "Hello there " + new Date() + 'app is running!';
const app = await render(AppComponent, {
componentProperties: {
title: title
}
});
expect(app).toBeTruthy();
expect(screen.getByText(new RegExp(title, "i"))).toBeInTheDocument();
screen.debug();
});
})
But getting an error as :
TestingLibraryElementError: Unable to find an element with the text: /Hello there Fri Mar 11 2022 20:07:42 GMT+0530 (India Standard Time)app is running!/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, <script />, <style />
<body>
<div
id="root0"
ng-version="13.1.3"
>
<h1>
Hello there Fri Mar 11 2022 20:07:42 GMT+0530 (India Standard Time)app is running! app is running!
</h1>
<router-outlet />
</div>
</body>
17 | });
18 | expect(app).toBeTruthy();
> 19 | expect(screen.getByText(new RegExp(title, "i"))).toBeInTheDocument();
| ^
20 | screen.debug();
21 | });
22 | })
Any one help me to understand the issue here? how to handle this scenario?
You have to escape the title before creating the RegExp because it contains regexp specific chars (+
, (
, )
).
const title = "Hello there " + new Date() + 'app is running!';
new RegExp(title, 'i').test(title)
// false