简体   繁体   中英

How to write test cases in React using Jest

I am working on a React project. And I am very new in writing Jest test cases. In my project I wrote a simple function and trying to test that function. But the test case is failing someone please help to overcome all errors.

This is App.js

import React from 'react';
import './App.css';
import Add from './Add/Add';

const App = () => {
  return (
    <div className='container'>
      <div className='row'>
        <div className='col-12'>
          <Add></Add>
        </div>
      </div>
    </div>
  )
}

export default App

This is Add.js

import React from 'react';

const Add = () => {
    const addition = () => {
        const a = 10;
        const b = 10;
        const c = a + b
        return c
    }
    const myNumber = addition()
    return (
        <div>
            {myNumber}
        </div>
    )
}

export default Add

This is Add.test.js

import { addition } from './Add';

it('Addition testing', () => {
    expect(addition()).toBe(20)
})

If you have any questions please put a comment

The problem is that the addition function is not exposed from Add.js . If you instead do

import React from 'react';

export const addition = () => {
    const a = 10;
    const b = 10;
    const c = a + b
    return c
}

const Add = () => {
    return (
        <div></div>
    )
}

export default Add

the test should pass.

If you want to use addition in your component you can do

import React from 'react';

export const addition = () => {
    const a = 10;
    const b = 10;
    const c = a + b
    return c
}

const Add = () => {
    const myNumber = addition();
    return (
        <div>{myNumber}</div>
    )
}

export default Add

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