简体   繁体   中英

How mock the component in React

I'm new in reactJS. I test my component RegisterForm with Jest .

I'm mock components that are already tested (eg PasswordField ). Therefore, i mock it but I have an error that appears:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Field`.

   9 | describe('HeaderContainer', () => {
  10 |     it('render correctly', ()=>{
> 11 |         const tree = renderer.create(
     |                               ^
  12 |            <RegisterForm />
  13 |         ).toJSON();
  14 |         expect(tree).toMatchSnapshot()

Do you know how I can solve the problem ?

this is my test:

import renderer from "react-test-renderer";
import React from "react";
import {RegisterForm} from "../../../../components/form";
import {PasswordField} from "../../../../components/textFields";


jest.mock('../../../../components/textFields', () => ('PasswordField'));

describe('HeaderContainer', () => {
    it('render correctly', ()=>{
        const tree = renderer.create(
           <RegisterForm />
        ).toJSON();
        expect(tree).toMatchSnapshot()

    })
});

You are using the named import in your test not the default one. You probably need

import RegisterForm from "...."

If you have some HOC around the RegisterForm and you are actually trying to use a named export then you have to export the component as well as the default export (might look something like)

export const RegisterForm = (props) => {}; //named export
export default RegisterForm; //default export

The error that you posted is pointing you towards that - or you might have mixed up default and named imports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM