使用 useEffect() 钩子在 Jest 中测试函数 [英] Using useEffect() hook to test a function in Jest

查看:96
本文介绍了使用 useEffect() 钩子在 Jest 中测试函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上正在学习 Jest,我必须为 useEffect() 钩子编写一个测试用例,该钩子基于 flag[counter] 进行渲染,并在内部检查某个字段是否存在 localStorage 值.

I'm learning Jest basically, I have to write a test case for the useEffect() hook which renders based on a flag[counter], and which internally checks if a localStorage value is present for a field.

function sample(props) {
  const counter = props;
  const [displayIcon, setDisplayIcon] = useState(counter);

  function isLocalstoragePresent() {    
    return localStorage.getItem("some_Id");
  }

  useEffect(() => {
    if (isLocalstoragePresent()) {
      setDisplayIcon(true);
    } else {
      setDisplayIcon(false);
    }
  }, [counter]);

 export default sample;

有人可以帮助我编写测试用例吗/为内部调用 isLocalstoragePresent() 方法的 UseEffect 提供指导.提前致谢.

Can some one help me in writing test case/provide a guidence for the UseEffect which internally calls isLocalstoragePresent() method aswell. Thanks in advance.

推荐答案

这是使用 jestjsreact-dom/test-utils 的单元测试解决方案:

index.tsx:

Here is the unit test solution using jestjs and react-dom/test-utils:

index.tsx:
{displayIcon ?'图标' : ''}</div>;}导出默认样本;

import React, { useState, useEffect } from 'react'; function sample(props) { const { counter } = props; const [displayIcon, setDisplayIcon] = useState(counter); function isLocalstoragePresent() { return localStorage.getItem('some_Id'); } useEffect(() => { if (isLocalstoragePresent()) { setDisplayIcon(true); } else { setDisplayIcon(false); } }, [counter]); return <div>{displayIcon ? 'icon' : ''}</div>; } export default sample;

index.test.tsx:

import Sample from './';
import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';

describe('60639673', () => {
  let container;
  beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it('should display icon', async () => {
    jest.spyOn(localStorage.__proto__, 'getItem').mockReturnValueOnce('1');
    const mProps = { counter: false };
    await act(async () => {
      render(<Sample {...mProps}></Sample>, container);
    });
    expect(container.querySelector('div').textContent).toBe('icon');
    expect(localStorage.__proto__.getItem).toBeCalledWith('some_Id');
    localStorage.__proto__.getItem.mockRestore();
  });

  it('should not display icon', async () => {
    jest.spyOn(localStorage.__proto__, 'getItem').mockReturnValueOnce('');
    const mProps = { counter: true };
    await act(async () => {
      render(<Sample {...mProps}></Sample>, container);
    });
    expect(container.querySelector('div').textContent).toBe('');
    expect(localStorage.__proto__.getItem).toBeCalledWith('some_Id');
    localStorage.__proto__.getItem.mockRestore();
  });
});

100% 覆盖率的单元测试结果:

unit test results with 100% coverage:

 PASS  stackoverflow/60639673/index.test.tsx (9.723s)
  60639673
    ✓ should display icon (41ms)
    ✓ should not display icon (8ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.242s

依赖版本:

"react": "^16.12.0",
"react-dom": "^16.12.0",
"jest": "^25.1.0"

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60639673

这篇关于使用 useEffect() 钩子在 Jest 中测试函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆