Skip to content

Latest commit

 

History

History
137 lines (99 loc) · 2.79 KB

Testing.md

File metadata and controls

137 lines (99 loc) · 2.79 KB

Fastify decorators

Testing

Table of content:

Configuring test framework

Jest <= 26

Not supported

Jest >= 27

Packages to be installed:

Configuration steps:

  1. Set type to module and enable experimental VM modules in package.json
  2. Set ts-jest ESM preset in Jest config
  3. Set jest-ts-webcompat-resolver as resolver

Example configuration:

package.json:

{
  "type": "module",
  "scripts": {
    "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
  }
}

jest.config.js:

export default {
  preset: 'ts-jest/presets/default-esm',
  // Note resolver required only when using imports with extensions
  resolver: 'jest-ts-webcompat-resolver',
};

Mocha

Packages to be installed:

Example configuration:

.mocharc.yml:

# Common Mocha options
bail: false
timeout: 10000
enable-source-maps: true
v8-stack-trace-limit: 100
extension:
  - 'ts'
# Enable experimental TS ESM loader
loader:
  - ts-node/esm
# Specify tests pattern
spec:
  - test/**/*.test.ts
  - test/**/*.spec.ts

Bootstrap whole server

It also possible to test application by bootstrap everything. It comparable to normal run. Difference is server will not run.

Note: read more at Fastify testing documentation

Example:

src/index.ts:

import fastify from 'fastify';

const instance = fastify({
  /* options */
});

/* your code */

export { instance };

test/auth.spec.ts:

import { instance } from '../src';

describe('Application: authorization', () => {
  beforeEach(() => {
    /* Setup logic for test */
  });
  afterEach(() => {
    /* Teardown logic for test */
  });

  it('should check credentials and reply with result', async () => {
    const payload = { login: 'test', password: 'test' };

    const result = await instance.inject({
      url: '/auth/authorize',
      method: 'POST',
      payload,
    });

    expect(JSON.parse(result.body)).toEqual({ message: 'ok' });
  });
});