5.3.1 • Published 2 months ago

@shopify/jest-koa-mocks v5.3.1

Weekly downloads
42,618
License
MIT
Repository
github
Last release
2 months ago

@shopify/jest-koa-mocks

Build Status Build Status License: MIT npm version

Utilities to easily stub Koa context and cookies. The utilities are designed to help you write unit tests for your Koa middleware without needing to set up any kind of actual server in your test environment. When test writing is easy and fun you'll want to write more tests. ✨😎

Installation

yarn add @shopify/jest-koa-mocks

Usage

The module has two named exports, createMockContext and createMockCookies.

You should usually be able to get away with most unit tests just using createMockContext.

import {createMockContext, createMockCookies} from '@shopify/jest-koa-mocks';

createMockContext

This function allows you to create fully stubbable koa contexts for your tests.

  export interface Options<
    CustomProperties extends Object,
    RequestBody = undefined
  > {
    url?: string;
    method?: RequestMethod;
    statusCode?: number;
    session?: Dictionary<any>;
    headers?: Dictionary<string>;
    cookies?: Dictionary<string>;
    state?: Dictionary<any>;
    encrypted?: boolean;
    host?: string;
    requestBody?: RequestBody;
    throw?: Function;
    redirect?: Function;
    customProperties?: CustomProperties;
  }

  createContext(options: Options)

Simple example

In the simplest case you call createMockContext, run your middleware passing the result in, and then assert against the context objects fields

import SillyViewCounterMiddleware from '../silly-view-counter';
import {createMockContext} from '@shopify/jest-koa-mocks';

describe('silly-view-counter', () => {
  it('iterates and displays new ctx.state.views', async () => {
    const ctx = createMockContext({state: {views: 31}});

    await SillyViewCounterMiddleware(ctx);

    expect(ctx.state.views).toBe(32);
    expect(ctx.status).toBe(200);
    expect(ctx.body).toBe({view: 32});
  });
});

Testing throws and redirects

ctx.throw and ctx.redirect are defaulted to jest.fn()s, allowing you to easily test that a request has redirected or thrown in your middleware.

import passwordValidator from '../password-validator';
import {createMockContext} from '@shopify/jest-koa-mocks';

describe('password-validator', () => {
  it('throws if no password query parameter is present', async () => {
    const ctx = createMockContext({url: '/validate'});

    await passwordValidator(ctx);

    expect(ctx.throw).toBeCalledWith(400);
  });

  it('redirects to /user if the password is correct', async () => {
    const ctx = createMockContext({url: '/validate?password=correct'});

    await passwordValidator(ctx);

    expect(ctx.redirect).toBeCalledWith('/user');
  });
});

Testing cookies

ctx.cookies is created using createMockCookies.

import oAuthStart from '../';
import {createMockContext} from '@shopify/jest-koa-mocks';

describe('oauthStart', () => {
  it('sets nonce cookie', () => {
    const oAuthStart = createOAuthStart(baseConfig);
    const ctx = createMockContext({
      url: `https://myCoolApp.com/auth`,
    });

    oAuthStart(ctx);

    expect(ctx.cookies.set).toBeCalledWith('shopifyNonce', fakeNonce);
  });
});

Testing apps using common koa libraries

createMockContext allows you to pass a requestBody and session key by default, so you should be able to test applications using the common body parsing or session libraries simply and quickly.

import login from '../login';
import {createMockContext} from '@shopify/jest-koa-mocks';

describe('password-validator', () => {
  it('sets session.user if body contains a valid password and username', async () => {
    const ctx = createMockContext({
      url: '/login',
      requestBody: {
        username: 'valid',
        password: 'valid',
      },
      session: {},
    });

    await login(ctx);

    expect(ctx.session.user).toMatchObject({
      username: 'valid',
      accessToken: 'dummy-access-token',
    });
  });
});

createMockCookies

Creates a mock cookies instance.

const cookies = createMockCookies({
  sessionID: 'something something',
  store: 'shop1',
  referrer: 'somewhere.io',
});

The returned object will have the signature

interface MockCookies {
  set(key: string, value: string): void;
  get(key: string): string;
  responseStore: Map<string, string>;
  requestStore: Map<string, string>;
}

The set and get functions are designed to mimic how actual koa cookie instances work. This means set will set a value to the responseStore, while get will retrieve values from the requestStore.

// will set to the response store
cookies.set('key', 'value');

// will get from the request store
cookies.get('key') !== 'value';
// => true

When testing against a mock cookies instance you can either assert against the set/get functions, or you can check if the appropriate value is in the expected store.

cookies.set('foo', 'bar');
expect(cookies.set).toBeCalledWith('foo', 'bar');
cookies.set('foo', 'bar');
expect(cookies.responseStore.get('foo')).toBe('bar');
5.3.1

2 months ago

5.3.0

4 months ago

5.2.0

6 months ago

5.1.1

2 years ago

5.1.0

2 years ago

5.0.2

2 years ago

5.0.1

2 years ago

5.0.0

2 years ago

4.0.0

3 years ago

3.1.5

3 years ago

3.1.3

3 years ago

3.1.2

3 years ago

3.1.1

3 years ago

3.1.0

3 years ago

3.1.4

3 years ago

3.0.8

3 years ago

3.0.7

3 years ago

3.0.6

3 years ago

3.0.5

3 years ago

3.0.4

3 years ago

3.0.3

3 years ago

3.0.2

3 years ago

3.0.1

3 years ago

3.0.0

4 years ago

2.3.4

4 years ago

2.3.3

4 years ago

2.3.2

4 years ago

2.3.1

4 years ago

2.3.0

4 years ago

2.2.4

4 years ago

2.2.3

4 years ago

2.2.2

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.10

5 years ago

2.1.9

5 years ago

2.1.8

5 years ago

2.1.7

5 years ago

2.1.6

5 years ago

2.1.5

5 years ago

2.1.4

5 years ago

2.1.3

6 years ago

2.1.2

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.15

6 years ago

2.0.14

6 years ago

2.0.12

6 years ago

2.0.11

6 years ago

2.0.10

6 years ago

2.0.9

6 years ago

2.0.8

6 years ago

2.0.7

6 years ago

2.0.6

7 years ago

2.0.5

7 years ago

2.0.4

7 years ago

2.0.3

7 years ago

2.0.2

7 years ago

1.0.2

7 years ago