import * as React from "react"
import { render } from "@testing-library/react"
import {
Trans,
I18nProvider,
TransRenderProps,
TransRenderCallbackOrComponent,
} from "../src"
import { setupI18n } from "@lingui/core"
import { mockConsole } from "@lingui/test-utils"
import { PropsWithChildren } from "react"
import { TransNoContext } from "./TransNoContext"
describe("Trans component", () => {
/*
* Setup context, define helpers
*/
const i18n = setupI18n({
locale: "cs",
messages: {
cs: {
"All human beings are born free and equal in dignity and rights.":
"Všichni lidé rodí se svobodní a sobě rovní co do důstojnosti a práv.",
"My name is {name}": "Jmenuji se {name}",
Original: "Původní",
Updated: "Aktualizovaný",
ID: "Translation",
},
},
})
const renderWithI18n = (node: React.ReactNode) =>
render({node})
const text = (node: React.ReactNode) =>
renderWithI18n(node).container.textContent
const html = (node: React.ReactNode) =>
renderWithI18n(node).container.innerHTML
/*
* Tests
*/
describe("should log console.error", () => {
const renderProp = ({ children }: TransRenderProps) => (
render_{children}
)
const component = ({ children }: TransRenderProps) => (
component_{children}
)
test.each<{
description: string
props: any
expectedLog: string
expectedTextContent: string
}>([
{
description:
"both `render` and `component` are used, and return `render`",
props: {
render: renderProp,
component,
},
expectedLog:
"You can't use both `component` and `render` prop at the same time.",
expectedTextContent: "render_Some text",
},
{
description:
"`render` is not of type function, and return `defaultComponent`",
props: {
render: "invalid",
},
expectedLog:
"Invalid value supplied to prop `render`. It must be a function, provided invalid",
expectedTextContent: "default_Some text",
},
{
description: "`component` is not of type function, and return ",
props: {
component: "invalid",
},
expectedLog:
"Invalid value supplied to prop `component`. It must be a React component, provided invalid",
expectedTextContent: "default_Some text",
},
])("when $description", ({ expectedLog, props, expectedTextContent }) => {
mockConsole((console) => {
const { container } = render(
{
return <>default_{translation}>
}}
>
,
)
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(expectedLog),
)
expect(container.textContent).toBe(expectedTextContent)
})
})
it("when there's no i18n context available", () => {
const originalConsole = console.error
console.error = vi.fn()
expect(() => render())
.toThrowErrorMatchingInlineSnapshot(`
[Error: Trans component was rendered without I18nProvider. Attempted to render message: undefined id: unknown. Make sure this component is rendered inside a I18nProvider.
This often happens when multiple instances of @lingui/react are installed (e.g. due to a version mismatch or misconfiguration in a monorepo). Verify you have only one version installed by running: npm ls @lingui/react (or pnpm why @lingui/react / yarn why @lingui/react).]
`)
expect(() =>
render(),
).toThrowErrorMatchingInlineSnapshot(`
[Error: Trans component was rendered without I18nProvider. Attempted to render message: some valid message id: unknown. Make sure this component is rendered inside a I18nProvider.
This often happens when multiple instances of @lingui/react are installed (e.g. due to a version mismatch or misconfiguration in a monorepo). Verify you have only one version installed by running: npm ls @lingui/react (or pnpm why @lingui/react / yarn why @lingui/react).]
`)
console.error = originalConsole
})
it("when deprecated string built-ins are used", () => {
const originalConsole = console.error
console.error = vi.fn()
// @ts-expect-error testing the error
renderWithI18n()
expect(console.error).toHaveBeenCalled()
// @ts-expect-error testing the error
renderWithI18n()
expect(console.error).toHaveBeenCalledTimes(2)
console.error = originalConsole
})
})
it("should follow jsx semantics regarding booleans", () => {
expect(
html(
{0}0> bar"}
values={{
0: false,
}}
components={{
0: ,
}}
/>,
),
).toEqual("foo bar")
expect(
html(
{0}0> bar"}
values={{
0: "lol",
}}
components={{
0: ,
}}
/>,
),
).toEqual("foo lol bar")
})
it("should render default string", () => {
expect(text()).toEqual("unknown")
expect(text()).toEqual(
"Not translated yet",
)
expect(
text(
,
),
).toEqual("Not translated yet, Dave")
})
it("should render translation", () => {
const translation = text(
,
)
expect(translation).toEqual(
"Všichni lidé rodí se svobodní a sobě rovní co do důstojnosti a práv.",
)
})
it("should render translation from variable", () => {
const msg =
"All human beings are born free and equal in dignity and rights."
const translation = text()
expect(translation).toEqual(
"Všichni lidé rodí se svobodní a sobě rovní co do důstojnosti a práv.",
)
})
it("should render component in variables", () => {
const translation = html(
John }} />,
)
expect(translation).toEqual("Hello John")
})
it("should render array of components in variables", () => {
const translation = html(
John, !],
}}
/>,
)
expect(translation).toEqual("Hello John!")
})
it("should render named component in components", () => {
const translation = html(
}}
/>,
)
expect(translation).toEqual(`Read the docs`)
})
it("should render nested named components in components", () => {
const translation = html(
, strong: }}
/>,
)
expect(translation).toEqual(
`Read the docs`,
)
})
it("should render components and array components with variable", () => {
const translation = html(
, strong: }}
values={{
name: [John, !],
}}
/>,
)
expect(translation).toEqual(
`Read the docs, John!`,
)
})
it("should render non-named component in components", () => {
const translation = html(
}}
/>,
)
expect(translation).toEqual(`Read the docs`)
})
it("should render nested elements with `asChild` pattern", () => {
function ComponentThatExpectsSingleElementChild(props: {
asChild: boolean
children?: React.ReactElement
}) {
if (props.asChild && React.isValidElement(props.children)) {
return props.children
}
return
}
const translation = html(
,
1: ,
}}
/>,
)
expect(translation).toEqual(`please sign in again`)
})
it("should render translation inside custom component", () => {
const Component = (props: PropsWithChildren) => (
{props.children}
)
const html1 = html()
const html2 = html(
{translation}
}
id="Original"
/>,
)
expect(html1).toEqual('Původní
')
expect(html2).toEqual('Původní
')
})
it("should render custom format", () => {
const translation = text(
,
)
expect(translation).toEqual("1,00 €")
})
it("should render custom formatter", () => {
const i18nWithFormatters = setupI18n({
locale: "de",
messages: {
de: { "msg.removed": "<0>{type, upper}0> wurde entfernt" },
},
formatters: {
upper: (value, { locale }) => String(value).toLocaleUpperCase(locale),
},
})
const { container } = render(
}}
/>
,
)
expect(container.innerHTML).toEqual("ALBUM wurde entfernt")
})
it("should render plural", () => {
const render = (count: number) =>
html(
A lot of them0>}}"
}
values={{
count,
}}
components={{
0: ,
}}
/>,
)
expect(render(0)).toEqual("Zero items")
expect(render(1)).toEqual("1 item")
expect(render(2)).toEqual(`2 A lot of them`)
})
describe("rendering", () => {
it("should render a text node with no wrapper element", () => {
const txt = html()
expect(txt).toEqual("Some text")
})
it("should render custom element", () => {
const element = html(
{translation}
}
id="Headline"
/>,
)
expect(element).toEqual(`Headline
`)
})
it("supports render callback function", () => {
const spy = vi.fn()
text(
{
spy(props)
return <>>
}}
/>,
)
expect(spy).toHaveBeenCalledWith({
id: "ID",
message: "Default",
translation: "Translation",
children: "Translation",
})
})
it("should take defaultComponent prop with a custom component", () => {
function ComponentFC(props: TransRenderProps) {
return {props.children}
}
const span = render(
,
).container.innerHTML
expect(span).toEqual(`Some text
`)
})
test.each([
{ component: null },
{ render: null },
])(
"should ignore defaultComponent when `component` or `render` is null",
(props) => {
function ComponentFC(props: TransRenderProps) {
return {props.children}
}
const translation = render(
,
).container.innerHTML
expect(translation).toEqual("Some text")
},
)
})
describe("component prop rendering", () => {
it("should render class component as simple prop", () => {
class ClassComponent extends React.Component {
render() {
return Headline
}
}
const element = html()
expect(element).toEqual("Headline
")
})
it("should render function component as simple prop", () => {
const propsSpy = vi.fn()
function ComponentFC(props: TransRenderProps) {
propsSpy(props)
const [state] = React.useState("value")
return {state}
}
const element = html()
expect(element).toEqual(`value
`)
expect(propsSpy).toHaveBeenCalledWith({
id: "Headline",
message: undefined,
translation: "Headline",
children: "Headline",
})
})
})
describe("I18nProvider defaultComponent accepts render-like props", () => {
function DefaultComponent(props: TransRenderProps) {
return (
<>
{props.children}
{props.id && {props.id}
}
{props.message && {props.message}
}
{props.translation && (
{props.translation}
)}
>
)
}
it("should render defaultComponent with Trans props", () => {
const markup = render(
,
)
expect(markup.queryByTestId("id")?.innerHTML).toEqual("ID")
expect(markup.queryByTestId("message")?.innerHTML).toEqual("Some message")
expect(markup.queryByTestId("translation")?.innerHTML).toEqual(
"Translation",
)
})
describe("TransNoContext", () => {
it("Should render without provider/context", () => {
const translation = render(
,
).container.textContent
expect(translation).toEqual(
"Všichni lidé rodí se svobodní a sobě rovní co do důstojnosti a práv.",
)
})
})
})
})