test: add Highlight test

This commit is contained in:
EnixCoda 2022-06-06 23:44:44 +08:00
parent 8716ce02e9
commit ef481d7d7e
2 changed files with 20 additions and 11 deletions

View file

@ -0,0 +1,15 @@
import { render } from '@testing-library/react'
import React, { ComponentProps } from 'react'
import { Highlight } from './Highlight'
function test(title: string, text: string, match?: ComponentProps<typeof Highlight>['match']) {
it(title, () => {
expect(render(<Highlight text={text} match={match} />).container.textContent).toBe(text)
})
}
test('sample', 'abc', undefined)
test('sample', 'abc', /./)
test('sample', 'abc', /../)
test('sample', 'abc', /.../)
test('sample', 'abc', /..../)

View file

@ -1,17 +1,11 @@
import * as React from 'react'
import * as React from 'react';
export const Highlight = React.memo(function Highlight(props: {
text: string
match?: RegExp | string
}) {
export const Highlight = React.memo(function Highlight(props: { text: string; match?: RegExp }) {
const { text, match } = props
const $match = React.useMemo(() => {
if (match) {
if (match instanceof RegExp) {
if (match.flags.includes('g')) return match
return new RegExp(match.source, 'g' + match.flags)
}
return new RegExp(match, 'g')
if (match instanceof RegExp) {
if (match.flags.includes('g')) return match
return new RegExp(match.source, 'g' + match.flags)
}
return null
}, [match])