这是我用testing-library
和angular
的测试代码。这里我使用title
变量作为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();
});
})
但是得到一个错误为:
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 | })
有人帮我理解这里的问题吗?如何处理这种情况?
在创建RegExp之前必须转义标题,因为它包含RegExp特定的字符(+
、(
、)
(。
const title = "Hello there " + new Date() + 'app is running!';
new RegExp(title, 'i').test(title)
// false