如何在React项目中使用Jest对由事件触发的函数执行单元测试。

huangapple go评论87阅读模式
英文:

How to perform unit testing on function invoked by event using Jest in React project

问题

component.js

  1. import { React, useState } from 'React'
  2. import Container from 'react-bootstrap/Container'
  3. import Row from 'react-bootstrap/Row'
  4. import Col from 'react-bootstrap/Col'
  5. import Form from 'react-bootstrap/Form'
  6. import DatePicker from 'react-datepicker'
  7. import Row from 'react-bootstrap/Row'
  8. ...
  9. ...
  10. function Details() {
  11. const [initialDate, setInitialDate] = useState(new Date());
  12. ...
  13. ...
  14. return (
  15. <DatePicker test-id="dPicker" selected={initialDate} onChange={(date) => setInitialDate(date)} />
  16. )
  17. }

I wanted to unit test the onchange function code for the above datepicker using Jest. What piece of code will help me?

英文:

component.js

  1. import {React,useState} from &#39;React&#39;
  2. import Container from &#39;react-bootstrap/Container&#39;
  3. import Row from &#39;react-bootstrap/Row&#39;
  4. import Col from &#39;react-bootstrap/Col&#39;
  5. import Form from &#39;react-bootstrap/Form&#39;
  6. import DatePicker from &#39;react-datepicker&#39;
  7. import Row from &#39;react-bootstrap/Row&#39;
  8. ...
  9. ...
  10. function Details (){
  11. const[initialDate, setInitialDate] = useState(new Date());
  12. ...
  13. ...
  14. return(
  15. &lt;DatePicker test-id=&quot;dPicker&quot; selected = {initialDate} onChange={(date) =&gt; setInitialDate(date)}
  16. )
  17. }

I wanted to unit test the onchange function code for above datepicker using Jest . What piece of code will help me?

答案1

得分: 1

We can use ByDisplayValue query to return the input, textarea, or select element that has the matching display value.

Since the initial date state is new Date(), we need to set a mock system date for it so that our test result will be stable no matter when and where (CI/CD server can be any region) running it. We need to use jest.setSystemTime(now?: number | Date) to set the current system time used by fake timers.

E.g.

example.tsx:

  1. import React, { useState } from "react";
  2. import DatePicker from "react-datepicker";
  3. export const Example = () => {
  4. const [startDate, setStartDate] = useState<Date | null>(new Date());
  5. return (
  6. <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />
  7. );
  8. };

example.test.tsx:

  1. import { fireEvent, render, screen } from "@testing-library/react"
  2. import '@testing-library/jest-dom';
  3. import React from "react"
  4. import { Example } from "./example"
  5. describe('76034834', () => {
  6. test('should pass', () => {
  7. jest
  8. .useFakeTimers('modern')
  9. .setSystemTime(new Date('2015-12-20'));
  10. render(<Example />);
  11. const input = screen.getByDisplayValue('12/20/2015');
  12. fireEvent.change(input, { target: { value: new Date('2014-01-02') } });
  13. expect(screen.getByDisplayValue('01/02/2014')).toBeInTheDocument();
  14. })
  15. })

Test result:

  1. PASS stackoverflow/76034834/example.test.tsx (7.151 s)
  2. 76034834
  3. should pass (34 ms)
  4. -------------|---------|----------|---------|---------|-------------------
  5. File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
  6. -------------|---------|----------|---------|---------|-------------------
  7. All files | 100 | 100 | 100 | 100 |
  8. example.tsx | 100 | 100 | 100 | 100 |
  9. -------------|---------|----------|---------|---------|-------------------
  10. Test Suites: 1 passed, 1 total
  11. Tests: 1 passed, 1 total
  12. Snapshots: 0 total
  13. Time: 7.455 s, estimated 8 s

Package versions:

  1. "react": "^16.14.0",
  2. "react-datepicker": "^4.11.0",
  3. "@testing-library/react": "^11.2.7",
  4. "jest": "^26.6.3",
英文:

We can use ByDisplayValue query to

> Returns the input, textarea, or select element that has the matching display value.

Since the initial date state is new Date(), we need to set a mock system date for it so that our test result will be stable no matter when and where(CI/CD server can be any region) running it. We need to use jest.setSystemTime(now?: number | Date) to

> Set the current system time used by fake timers

E.g.

example.tsx:

  1. import React, { useState } from &quot;react&quot;;
  2. import DatePicker from &quot;react-datepicker&quot;;
  3. export const Example = () =&gt; {
  4. const [startDate, setStartDate] = useState&lt;Date | null&gt;(new Date());
  5. return (
  6. &lt;DatePicker selected={startDate} onChange={(date) =&gt; setStartDate(date)} /&gt;
  7. );
  8. };

example.test.tsx:

  1. import { fireEvent, render, screen } from &quot;@testing-library/react&quot;
  2. import &#39;@testing-library/jest-dom&#39;;
  3. import React from &quot;react&quot;
  4. import { Example } from &quot;./example&quot;
  5. describe(&#39;76034834&#39;, () =&gt; {
  6. test(&#39;should pass&#39;, () =&gt; {
  7. jest
  8. .useFakeTimers(&#39;modern&#39;)
  9. .setSystemTime(new Date(&#39;2015-12-20&#39;));
  10. render(&lt;Example /&gt;);
  11. const input = screen.getByDisplayValue(&#39;12/20/2015&#39;);
  12. fireEvent.change(input, { target: { value: new Date(&#39;2014-01-02&#39;) } });
  13. expect(screen.getByDisplayValue(&#39;01/02/2014&#39;)).toBeInTheDocument();
  14. })
  15. })

Test result:

  1. PASS stackoverflow/76034834/example.test.tsx (7.151 s)
  2. 76034834
  3. should pass (34 ms)
  4. -------------|---------|----------|---------|---------|-------------------
  5. File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
  6. -------------|---------|----------|---------|---------|-------------------
  7. All files | 100 | 100 | 100 | 100 |
  8. example.tsx | 100 | 100 | 100 | 100 |
  9. -------------|---------|----------|---------|---------|-------------------
  10. Test Suites: 1 passed, 1 total
  11. Tests: 1 passed, 1 total
  12. Snapshots: 0 total
  13. Time: 7.455 s, estimated 8 s

package versions:

  1. &quot;react&quot;: &quot;^16.14.0&quot;,
  2. &quot;react-datepicker&quot;: &quot;^4.11.0&quot;,
  3. &quot;@testing-library/react&quot;: &quot;^11.2.7&quot;,
  4. &quot;jest&quot;: &quot;^26.6.3&quot;,

huangapple
  • 本文由 发表于 2023年4月17日 19:45:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定