前端测试相关知识(单元测试、自动化测试)

单元测试

React17默认采用的testing-library

React参考https://testing-library.com/docs/react-testing-library/intro

package.json

"devDependencies": { 
  "@testing-library/jest-dom": "^5.14.1",
  "@testing-library/react": "^11.2.7",
  "@testing-library/react-hooks": "^7.0.2",
  "@testing-library/user-event": "^13.1.9",
  "msw": "^0.38.1",
  "jest": "^27.5.1",
}

setupTests.js

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import server from 'tests/Mock/service.mock';

// Establish API mocking before all tests.
beforeAll(() => {
  // onUnhandledRequest is optional
  server.listen({ onUnhandledRequest: 'warn' });
});

// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers());

// Clean up after the tests are finished.
afterAll(() => server.close());
tests/Mock/service.mock.js
import { rest } from 'msw';
import { setupServer } from 'msw/node';
export const handlers = [
  rest.get('/api/user/XXX', (req, res, ctx) => {
    return res(
      ctx.json([])
    );
  }),
  rest.put('/api/user/XXX', (req, res, ctx) => {
    return res(ctx.status(200));
  }),

  rest.post('/api/user/XXX', (req, res, ctx) => {
    return res(ctx.json([]));
  }),
];
export default setupServer(...handlers)
tests/test-utils.tsx
import React from 'react';
import { store } from 'store';
import { Provider } from 'react-redux';
import { ThemeProvider } from 'XXX';
import { render, RenderOptions } from '@testing-library/react';

const AllTheProviders: React.FC = ({ children }) => {
  return (
    <Provider store={store}>
      <ThemeProvider theme="dark">{children}</ThemeProvider>
    </Provider>
  );
};

const customRender = (ui: React.ReactElement, options?: Omit<RenderOptions, 'queries'>) =>
  render(ui, { wrapper: AllTheProviders, ...options });

export * from '@testing-library/react';

export { customRender as render };
xxx.spec.tsx
import XXX from 'components/XXX';
import { render, screen, cleanup } from 'tests/test-utils';

describe('Test XXX.tsx', () => {
  it('test render', async () => {
    render(<XXX />);
    const findTexts = await screen.findAllByText('XXX');
    expect(findTexts.length).toBeGreaterThan(0);
  });
});

 

自动化测试

可以使用python + selenium,具体参考我的博客