简体   繁体   中英

test method with jest and react-testing-library

i can´t get the answer, how cant reach the method inside a functional component iin react using jest and react-testing-library.

I tried with enzyme but i see all is changing to RTL.

import React from "react";

const simpleComponents = (props) => {

    const simpleMethod = () =>{ 
        // method logic
    };

    return <h1>test</h1>;
    };
}

export default simpleComponents;

You should try to test only what your user would see in a real browser, and not your component internal logic. This is what react-testing-library promotes: writing tests that give confidence because they see/do what a real user would.

https://testing-library.com/docs/guiding-principles

Following these guidelines, you should try to build a test which triggers user interactions on visible elements (rendered by your component), and which would involve the execution of simpleMethod.

This is the whole point of react-testing-library queries: getByText, getByPlaceholder, getByRole: things that a real user would see, hiding internal logic. But I guess you could have this approach with Enzyme (I never used Enzyme).

Writing tests with this approach leads to less tests, but stronger ones, which IMHO is a good thing. It is quite different from classical unit tests (say in a Java context for example) where you tests functions, inputs, outputs...

In fact your React component is a function, its inputs are user interactions, its output is a DOM.

simpleMethod function is defined in the private scope of simpleComponents SFC. It's not exposed, so you can't get the function outside of simpleComponents .

But you can test it indirectly, for example:

const simpleMethod = () =>{ 
  console.log('method logic');
};

Firstly, you need to use an event such as click , submit to trigger it. We add a console.log method, so we can spy on the console.log method, to check if simpleMethod function is called or not.

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