reactjs - Jest fn ile React fonksiyonel bileşenini taklit ederken Typescript hatası


Testimin içine, çağrılıp çağrılmadığını takip etmek için sahte bir bileşen oluşturdum, test düzgün çalışıyor. Ancak Visual Studio Code, yukarıdaki kod için sürekli olarak aşağıdaki hatayı veriyor:

MockedComponent' cannot be used as a JSX component. Its instance type 'Element' is not a valid JSX element.ts(2786)

Bilen var mı neden VSCode bana bu hatayı veriyor?

benim-testim.test.tsx
test('should do something', () => {
    const MockedComponent = jest.fn((props: SomeProps) => {
      return <div>{props.foo}</div>
    })

    render(
      <div>
        <MockedComponent foo="bar" />
      </div>
    )

    expect(MockedComponent).toHaveBeenCalled()
  })
VSCode hatası
MockedComponent' cannot be used as a JSX component. Its instance type 'Element' is not a valid JSX element.ts(2786)

Cevap #1

Bu testin mantıklı olmasının tek yolu, bu bileşeni başka bir bileşene geçirmeniz ve onun render edildiğinden emin olmanızdır.

Ve bunu yaptığınızda, hiçbir sorun yok. Bu test sorunsuz çalışıyor.

function MyComp({
  C,
  cProps
}: {
  C: (props: { foo: string }) => JSX.Element
  cProps: { foo: string }
}) {
  return (
    <div>
      <C foo={cProps.foo} />
    </div>
  )
}

const MockedComponent = jest.fn((props: { foo: string }) => {
  return <div>{props.foo}</div>
})

render(<MyComp C={MockedComponent} cProps={{ foo: 'bar' }} />)

expect(MockedComponent).toHaveBeenCalledWith({ foo: 'bar' })

jest.fn() ile ilgili olarak TypeScript'i neden mutsuz ettiğini tam olarak bilmiyorum, ama onu anlamlı şekilde kullandığınızda hata ortadan kayboluyor.

Yani, böyle doğrudan bir mocklanmış bileşeni render etmeyin (çünkü, A: işe yaramaz ve B: zaten bunu yapmak herhangi bir anlam ifade etmez), ve sorun yaşamazsınız.