Arrange / Act / Assert in tests

Posted 2023-10-15

This is part of my notes section of the site. It is where I post quick notes/cheatsheets/etc.
For more in-depth articles which are (hopefully) more interesting check out my blog


If you have written tests before you are probably familiar with arrange / act / assert

They are the 3 main parts to a test.

  • in arrange you set up the test.
    • For example, create a blog post object to pass in as a prop, or set up some mocked functions
  • in act you run the unit under code
    • in other words: run the thing you're testing
    • For simple tests without interaction this can just be render(<YourComponent />
    • But for most tests the render(...) call will be more of arrange, and the act section will be interacting (e.g. with clicks on buttons or typing into text inputs)
  • in assert you run your assertions to check the result
    • with jest, this will be your expect(result).toBe(expectedResult) code
    • this can be either:
      • the returned result (from 'act'),
      • what it rendered (for React components
      • or maybe some side effect (did it call window.fetch? Were new cookies set? etc)
example.test.jsx
✅ copied
test('calls login function when login button is clicked', () => { // Arrange const mockLogin = jest.fn(); render(<LoginButton login={mockLogin} />); // Act const loginButton = getByText('Log In'); fireEvent.click(loginButton); // Assert expect(mockLogin).toHaveBeenCalled(); });

Subscribe to my
Full Stack Typescript Developer
newsletter

If you enjoyed my content and want more Full Stack Typescript content, then enter your email below.

I send a few links every couple of weeks, that I personally found useful from around the web.

Focusing on Testing, Typescript, NextJS, and also
engineering soft skills posts.

Welcome to my site and blog - Code Driven Development.

This is the 'notes' section, which I use to quickly write up blog posts. For more in depth and longer posts check out My blog