Jest
Expecting/Asserting¶
Expecting objects¶
'.toMatchObject' vs 'objectContaining'
objectContaining: nested properties need to be exact
// FAIL
expect({ position: { x: 0, y: 0 } }).toEqual(expect.objectContaining({
  position: {
    x: expect.any(Number)
  }
}));
// PASS
expect({ position: { x: 0, y: 0 } }).toMatchObject({
  position: {
    x: expect.any(Number)
  }
});
Expect an error¶
Wrap it in an anon function
Mocking¶
like Python patching except with the intuitive API where you mock the imports just in the tests
Mocking modules¶
- has to be at the top of the file
- can't be in a test
Expecting mocks¶
expect(Component).toHaveBeenCalledWith()
Cleaning up mocks¶
Test configuration¶
<rootDir>/jest.config.json
{
  "preset": "ts-jest",
  "transform": {
    "^.+\\.(ts|tsx|js|jsx)$": "ts-jest",
    // because Jest doesn't know what to do with 
    "^.+\\.svg$": "<rootDir>/tests/__mocks__/svgTransform.js"
  },
  "setupFiles": ["<rootDir>/tests/setupTests.js"],
  "setupFilesAfterEnv": ["<rootDir>/tests/setupJestAfterEnv.js"],
  "moduleNameMapper": {
    "^.+\\.(css|scss)$": "identity-obj-proxy",
    "^@src(.*)$": "<rootDir>/src$1",
    "^@tests(.*)$": "<rootDir>/tests$1",
    "^@stories(.*)$": "<rootDir>/stories$1",
    "^.+\\.(svg)$": "<rootDir>/tests/__mocks__/fileMock.js"
  },
  "transformIgnorePatterns": ["node_modules/(?!react-data-grid/lib)"],
  "modulePathIgnorePatterns": ["<rootDir>/dist/"],
  "globals": {
    "REACT_APP_API_ROOT": "http://localhost:8000"
  },
  "bail": true
}
  
    
      Last update:
      2023-04-24