当前位置: 首页 > 工具软件 > JTest > 使用案例 >

Jtest测试

花品
2023-12-01

RN

render

import {render} from '@testing-library/react-native';
describe('...', () => {
  test('.....', () => {
    const {getAllByTestId} = render(<组件名 />);
    const a = getAllByTestId('testID');
    expect(a).toHaveLength(4);// 长度
    expect(a).toHaveStyle({opacity: 0});// 样式
  });
  
  test('.....', () => {
    const {getByText} = render(
      <组件名/>,
    );
    const labelText = getByText('...');
    expect(labelText).toBeTruthy();// 存在文本
  });
  
  test('...', () => {
    const {getByText} = render(
      <RecoilRoot>
        <Consent />
      </RecoilRoot>,
    );

    const title = getByText('...');
    const body = getByText(RegExp('正则表达式'));

    expect(title).toBeTruthy();
    expect(body).toBeTruthy();
  });
}

act

import {act} from 'react-test-renderer';
test('...', () => {
  const {getByText, getByTestId} = render(
    <RecoilRoot>
      <Consent />
    </RecoilRoot>,
  );
  const nextButton = getByTestId('nextButton');
  act(() => {
    nextButton.props.onClick();
  });
  const errorMessage = getByText(
    '...',
  );
  expect(errorMessage).toBeTruthy();
});

fireEvent

import {fireEvent, render} from '@testing-library/react-native';
  test('...', () => {
    const {getByText, getByTestId} = render(
      <RecoilRoot>
        <Consent navigation={{navigate: jest.fn()}} />
      </RecoilRoot>,
    );
    const nextButton = getByTestId('nextButton');
    const checkboxContainer = getByTestId('checkboxContainer');
    fireEvent.press(checkboxContainer);
    act(() => {
      nextButton.props.onClick();
    });

    const errorMessage = getByText(
      '...',
    );

    expect(errorMessage).toBeTruthy();
  });
});

Mock Recoil

import {useRecoilValue} from 'recoil';
jest.mock('recoil');
describe('...', () => {
  it('...', () => {
    useRecoilValue.mockImplementation(() => ({
      firstName: jr,
      lastName: 'h',
    }));
    const {findAllByText} = render(<EnrollmentSuccessCard />);
    expect(findAllByText('jr h')).toBeTruthy();
  });
});
beforeEach(() => {
  useRecoilState.mockImplementation(() => [['', ''], jest.fn()]);
  useRecoilValue.mockImplementation(() => [
    '0623',
    '2306',
    ...pinCodeAntiPatterns,
  ]);
});

queryByText and queryByPlaceholderText

  • queryByText是用过text来查找对应的dom,没有找到会返回null,而getByText在没找到对应的DOM时会直接报错。
it('displays ...', () => {
  const {queryByPlaceholderText, queryByText} = render(
    <RecoilRoot>
      <组件 />
    </RecoilRoot>,
  );
  expect(queryByText('..')).toBeTruthy();
  expect(queryByPlaceholderText('...')).toBeTruthy();
});

Response

let mockAuthResponse = Promise.resolve();

jest.mock('../../../../modules/ec', () => ({
  ec: {
    a: () => mockAuthResponse,
    b: jest.fn().mockImplementation(() => ({
      catch: jest.fn(),
    })),
  },
}));

let mockMessageData = {};

jest.mock('@react-native-firebase/messaging', () => ({
  firebase: {
    messaging: jest.fn().mockImplementation(() => ({
      onMessage: jest.fn((callback) => callback({data: mockMessageData})),
    })),
  },
}));

const mockNavigation = {
  navigate: jest.fn(),
};

const updateLocation = jest.fn();

const mockLocationData = {
 ...
};
beforeEach(() => {
  mockMessageData = {};
  mockAuthResponse = Promise.resolve();
});

swr and mockResponseOnce

import {cache} from 'swr';
describe('..', () => {
  beforeEach(() => cache.clear());
  test('should display user name', () => {
    fetch.mockResponseOnce(
      JSON.stringify({first_name: 'First', last_name: 'Last'}),
    );

    const {queryByText} = render(
      <RecoilRoot>
        <PassCard />
      </RecoilRoot>,
    );

    act(() => {
      jest.runAllTicks();
    });

    expect(queryByText('First Last')).toBeTruthy();
  });
});

navigation

import {cache} from 'swr';
const navigation = {
  reset: jest.fn(),
  navigate: jest.fn(),
};

describe('..', () => {
  beforeEach(() => cache.clear());
  it('.....', () => {
    const {getByLabelText} = render(
      <RecoilRoot>
        <Home navigation={navigation} route={{}} />
      </RecoilRoot>,
    );
    act() => {
      jest.runAllTicks();
    });
    fireEvent.press(getByLabelText('a'));
    expect(navigation.reset).toBeCalledWith({
      routes: [
        {
          name: '..',
          state: {
            routes: [{name: '..'}],
          },
        },
      ],
    });
  });

react

renderHook

jest.mock('../useErrorHandling');
jest.mock('swr');
jest.mock('../../utils/isFCMSupported');
describe('..', () => {
  test('...', () => {
    const locationIds = [];
    isFCMSupported.mockReturnValue(true);
    renderHook(() => useActivityLog({locationIds}));
    expect(useSWR).toBeCalledWith(null, fetcher, {refreshInterval: 0});
  });

  test('...', async () => {
    const locationIds = ['1234'];

    useSWR.mockReturnValue({data: mockActivityLogData});
    fetch.mockResolvedValueOnce({json: () => ..});
    const {.., ..} = renderHook(() =>
      useActivityLog({locationIds})
    );
    await waitForNextUpdate();

    expect(result.current.logs).toEqual([
      {
       ...
  });
});
 类似资料: