Jest and Droids

Jest and Droids

July 30, 2024
2024, Engineering
React, Nextjs, Notes

Introduction #

In this post we will look at

  1. How to setup Jest for NextJS projects
  2. Setting up Android on Ubuntu

Setting up Jest to existing NextJS projects #

Jest is a good testing framework which makes easy practicing TDD on ReactJS projects. There are two ways of integrating Jest into NextJS projects:

When starting from scratch #

Its as easy as running following command:

npx create-next-app@latest --example with-jest with-jest-app

In this case with-jest-app will be created for us

A fun fact Jest can also be used to test Mobile Apps

When integrating with existing projects #

For existing projects its a little bit tricky. We need to run following commands

npm install -D jest ts-node jest-environment-jsdom @testing-library/react @testing-library/jest-dom @types/jest
npm init jest@latest

Note: When running npm init jest@latest command ensure we choose Typscript for configuration step. Basically choose Y for Would you like to use Typescript for the configuration file? question

Once this is done we need to update Jest’s config file as mentioned in official documentation. We need to update jest.config.ts to

import type { Config } from 'jest'
import nextJest from 'next/jest.js'
 
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})
 
// Add any custom config to be passed to Jest
const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
 
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

To check if your setup is correct run npm run test and see if Jest runs successfully

Note about CI #

Remember to add npm run test as one of the build steps for you CI

Writing a simple test #

Now that we’ve got Jest working, lets write a simple test. Lets assume that we have a simple function as follows

export const addNums = (first: number, second: number): number => {
  return first - second;
}

Take a note of the error we’ve induced knowingly where we’re returning difference as opposed to sum of two numers.

Next we will create a __tests__ directory at same level of apps directory. The file that we will create will be simple.test.tsx. It should look like

import { addNums } from "@/utils/Tracker";


describe('Simple calculator', () => {
    it('Should add two numbers', () => {
        expect(addNums(1, 3)).toBe(4);
    })
});

Take a note of you import statement it might change with your project. Now run npm run test from location where package.json file is located. If things work well you should get trace like follows

 FAIL  src/__tests__/simple.test.tsx
  Simple calculator
    ✕ Should add two numbers (3 ms)

  ● Simple calculator › Should add two numbers

    expect(received).toBe(expected) // Object.is equality

    Expected: 4
    Received: -2

      4 | describe('Simple calculator', () => {
      5 |     it('Should add two numbers', () => {
    > 6 |         expect(addNums(1, 3)).toBe(4);
        |                               ^
      7 |     })
      8 | });

      at Object.<anonymous> (src/__tests__/simple.test.tsx:6:31)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.445 s
Ran all test suites.

Fix the code and run test again it should pass

(node:94058) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 PASS  src/__tests__/simple.test.tsx
  Simple calculator
    ✓ Should add two numbers (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.409 s, estimated 1 s
Ran all test suites.

Cavets #

At times running npm run build it might fail if the config is not correct. So take care while running the code.

Setting up Android for Ubuntu #

Android setup entails following:

  1. Downloading android studio
  2. The way I’ve preffered installing it is creating ~/Installs/tools/ directory and placing the tar file there
  3. Un tar the file tar xvfz android-studio-2024.1.1.12-linux.tar.gz
  4. Complete setup of Android studio, just execute ./bin/studio.sh from SDK’s directory
  5. Once done we need to update PATH in our ~/.basrc file include following lines
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/platform-tools

You should be all set. Connect device and run adb devices