import {useContextSection, useContext} from '.';
import {createContext} from 'use-context-selector';
import {act, renderHook} from '@testing-library/react';
import {useState} from 'react';

describe('context hooks', function() {
  it('useContextSection, useContext类型正确', function() {
    expect(useContextSection).toBeDefined();
    expect(useContext).toBeDefined();

    expect(useContextSection).toBeInstanceOf(Function);
    expect(useContext).toBeInstanceOf(Function);
  });

  it('useContextSection 返回值检测', function() {
    const {result} = renderHook(function() {
      const state = useState({name: '', age: 2});
      const context = createContext(state);
      return useContextSection(context, state => state);
    });

    expect(result.current[0]).toEqual({name: '', age: 2});

    act(function() {
      result.current[1](val => ({...val, name: 'simon'}));
    });

    expect(result.current[0]).toEqual({name: 'simon', age: 2});
  });

  it('useContextSection 防止重新渲染', function() {
    const {result} = renderHook(function() {
      const state = useState({name: '', age: 2});
      const context = createContext(state);

      const section1 = useContextSection(context, function([{name}, dispatch]) {
        return [name, dispatch] as const;
      });

      const section2 = useContextSection(context, function([{age}, dispatch]) {
        return [age, dispatch] as const;
      });

      return {section1, section2};
    });

    const memoState = result.current.section1;

    act(function() {
      result.current.section2[1](prev => ({...prev, age: 12}));
    });

    expect(memoState).toBe(result.current.section1);
  });
});
