How to test jsoneditor in react component

1.1k views Asked by At

I'm using jsoneditor in my react componet

example code:

import React, { useEffect, useRef } from 'react'
import JSONEditor from "jsoneditor";
import 'jsoneditor/dist/jsoneditor.css';

export const JsonPanel = ({ json }: any) => {
    const jsonRef = useRef<HTMLDivElement | null>(null)

    useEffect(() => {
        let jsonEditor: JSONEditor | null = null
        if (jsonRef.current) {
            jsonEditor = new JSONEditor(jsonRef.current, {
                modes: ['code', 'tree']
            }, json);
        }
        return () => jsonEditor?.destroy()
    }, [json])

    return (
        <div id='json-panel' ref={jsonRef} />
    )
}

It works well when the app runs. However, I'm unable to test this component using @testing-library/react

example code:

import React from 'react';
import { render, screen } from '@testing-library/react';
import { JsonPanel } from './JsonPanel';

describe('<JsonPanel />', () => {
    it('should render json', async () => {
        render(<JsonPanel json={{ key: "value" }} />)

        expect(screen.getByText("key")).toBeInTheDocument();
    })
})

The problem is, the render result doesn't contain any json content in the json-panel html element. it looks from the jest test error output, JSONEditor is injected to that html element but there is no json content.

error output: https://gist.github.com/Doraemoe/6aa1288ef3693280ff503b9c68a7896f

Is there something I'm missing here? Thanks.

0

There are 0 answers