References

Run a single test / file

# From 2019
npm test -- path/to/file.spec.js

Basic

Sample

👇 https://dev.to/jackcaldwell/mocking-es6-class-methods-with-jest-bd7

// We wanna mock this class
export class ProductsClient {
  async getById(id) {
    const url = `http://localhost:3000/api/products/{id}`;
    const response = await fetch(url);
    return await response.json();
  }
}

// We wanna test this class
export class ProductManager {
  async getProductToManage(id) {
    const productsClient = new ProductsClient();
    const productToManage = await productsClient.getById(id)
      .catch(err => alert(err));
    return productToManage;
  }
}
// In the file of testing class ProductManager
import { ProductsClient } from './ProductsClient';
jest.mock('./ProductsClient');

// A "mock" getById() which returns "undefined" will be created
// But we want the mock function returns a value as we want

// assign a mock function to the ProductsClient's 'getById' method
const mockGetById = jest.fn();
ProductsClient.prototype.getById = mockGetById;
// We can make the mock function return what we want
mockGetById.mockReturnValue(Promise.resolve(expectedProduct));

// Restore the state of the original class
mockFn.mockClear() // or something like that (check the doc)

Folder conventions

(SO source) The conventions for Jest, in order of best to worst in my opinion:

  1. src/file.test.js mentioned first in the Getting Started docs, and is great for keeping tests (especially unit) easy to find next to source files
  2. src/__tests__/file.js lets you have multiple __tests__ directories so tests are still near original files without cluttering the same directories
  3. __tests__/file.js more like older test frameworks that put all the tests in a separate directory; while Jest does support it, it's not as easy to keep tests organized and discoverable

Testing with Date()

Becareful that,

For example, "2011-10-10" (date-only form), "2011-10-10T14:48:00" (date-time form), or "2011-10-10T14:48:00.000+09:00" (date-time form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

→ Sử dụng UTC time sẽ an toàn hơn (và ko bị ảnh hưởng bởi local time hay timezone)

Differences