DEV Community

YashasaveeKesarwani99
YashasaveeKesarwani99

Posted on

To do list app with react typescript and react testing library

Using typescript and testing code with react testing library

Typescript really makes it easy for developers to know the type of variables and return type of the functions which are in play.

I have used hooks for managing states, one can mention the type of state they are defining which makes its type unchangeable resulting in lesser discrepancy issues.

  const [task,setTask] = useState<string>("");
  const [tasks,setTasks] = useState<Array<string>>([])
Enter fullscreen mode Exit fullscreen mode

The type of props should be defined before using them in the children component which can be done using type or interface keyword.

type props = {
    setTask:React.Dispatch<React.SetStateAction<string>>
    tasks:string[] 
    setTasks:React.Dispatch<React.SetStateAction<string[]>>
    task:string
}
Enter fullscreen mode Exit fullscreen mode

For testing purpose I've used react testing library to do simple unit and integration testing.

const mockSetTask = jest.fn()
const mockSetTasks = jest.fn()

var task:string
var tasks:string[] = []

it('gets input from input component',  ()=>{
        render(<Input  setTask={mockSetTask} setTasks={mockSetTasks} tasks={tasks} task={task}/>)
        const ele = screen.getByPlaceholderText("Enter Task") as HTMLInputElement

        fireEvent.change(ele,{target:{value:'Go To Gym'}})
        expect(ele.value).toBe('Go To Gym')
    })
Enter fullscreen mode Exit fullscreen mode

Github Repo : To do list app

Top comments (0)