Unit testing

  • unit
    • A partially independent block of code in a program that performs a specific task
  • Unit testing
    • A test that tests a separate code module

When you’re doing unit testing, it’s important to know what the responsibilities of the object you’re testing are if method 1 depends on method 2, okay

  • Depend on the shape, such as
Graph TD Dependent-Module- dependency & Input --> Function --> Output

Mock Function

  • Set the return value
const mockCallback = jest.fn();
mockCalback.mockReturnValue(true);
Copy the code
  • Analog function implementation
const mockCallback = jest.fn();
mockCalback.mockImplementation(()=>true);
Copy the code
  • Verify that the function is called
// Verify that the function is called expect(mockCallback).tohaveBeencalled (); // Verify how many times the function is called expect(mockCallback).tohaveBeencalledTimes (4); ToHaveBeenCalledWith (2); // Verify that the function is called with an argument.Copy the code
  • Declare a Mock Function

    • location
      • Add declared methods to describe
    • code
    jest.mock("./verify")
    Copy the code

    The module can be invoked after the declaration. Custom components write paths

  • Test Async/Await syntax

test('... ', asyn ()=> { await expect((fetchData)).resolves.toBe('... '); }) test('... ', asyn ()=> { await expect((fetchData)).rejects.toThrow('error'); })Copy the code