UNPKG

5.51 kBMarkdownView Raw
1# `@shopify/jest-koa-mocks`
2
3[![Build Status](https://travis-ci.org/Shopify/quilt.svg?branch=master)](https://travis-ci.org/Shopify/quilt)
4[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE.md) [![npm version](https://badge.fury.io/js/%40shopify%2Fjest-koa-mocks.svg)](https://badge.fury.io/js/%40shopify%2Fjest-koa-mocks)
5
6Utilities 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. ✨😎
7
8## Installation
9
10```bash
11$ yarn add @shopify/jest-koa-mocks
12```
13
14## Usage
15
16The module has two named exports, `createMockContext` and `createMockCookies`.
17
18You should usually be able to get away with most unit tests just using `createMockContext`.
19
20```js
21import {createMockContext, createMockCookies} from '@shopify/jest-koa-mocks';
22```
23
24### createMockContext
25
26This function allows you to create fully stubbable koa contexts for your tests.
27
28```typescript
29 export interface Options<
30 CustomProperties extends Object,
31 RequestBody = undefined
32 > {
33 url?: string;
34 method?: RequestMethod;
35 statusCode?: number;
36 session?: Dictionary<any>;
37 headers?: Dictionary<string>;
38 cookies?: Dictionary<string>;
39 state?: Dictionary<any>;
40 encrypted?: boolean;
41 host?: string;
42 requestBody?: RequestBody;
43 throw?: Function;
44 redirect?: Function;
45 customProperties?: CustomProperties;
46 }
47
48 createContext(options: Options)
49```
50
51#### Simple example
52
53In the simplest case you call `createMockContext`, run your middleware passing the result in, and then assert against the context objects fields
54
55```typescript
56import SillyViewCounterMiddleware from '../silly-view-counter';
57import {createMockContext} from '@shopify/jest-koa-mocks';
58
59describe('silly-view-counter', () => {
60 it('iterates and displays new ctx.state.views', async () => {
61 const ctx = createMockContext({state: {views: 31}});
62
63 await SillyViewCounterMiddleware(ctx);
64
65 expect(ctx.state.views).toBe(32);
66 expect(ctx.status).toBe(200);
67 expect(ctx.body).toBe({view: 32});
68 });
69});
70```
71
72#### Testing throws and redirects
73
74`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.
75
76```typescript
77import passwordValidator from '../password-validator';
78import {createMockContext} from '@shopify/jest-koa-mocks';
79
80describe('password-validator', () => {
81 it('throws if no password query parameter is present', async () => {
82 const ctx = createMockContext({url: '/validate'});
83
84 await passwordValidator(ctx);
85
86 expect(ctx.throw).toBeCalledWith(400);
87 });
88
89 it('redirects to /user if the password is correct', async () => {
90 const ctx = createMockContext({url: '/validate?password=correct'});
91
92 await passwordValidator(ctx);
93
94 expect(ctx.redirect).toBeCalledWith('/user');
95 });
96});
97```
98
99#### Testing cookies
100
101`ctx.cookies` is created using [`createMockCookies`](/README.md#createmockcookies).
102
103```typescript
104import oAuthStart from '../';
105import {createMockContext} from '@shopify/jest-koa-mocks';
106
107describe('oauthStart', () => {
108 it('sets nonce cookie', () => {
109 const oAuthStart = createOAuthStart(baseConfig);
110 const ctx = createMockContext({
111 url: `https://myCoolApp.com/auth`,
112 });
113
114 oAuthStart(ctx);
115
116 expect(ctx.cookies.set).toBeCalledWith('shopifyNonce', fakeNonce);
117 });
118});
119```
120
121#### Testing apps using common koa libraries
122
123`createContext` allows you to pass a `body` and `session` key by default, so you should be able to test applications using the common body parsing or session libraries simply and quickly.
124
125```javascript
126import login from '../login';
127import {createMockContext} from '@shopify/jest-koa-mocks';
128
129describe('password-validator', () => {
130 it('sets session.user if body contains a valid password and username', async () => {
131 const ctx = createMockContext({
132 url: '/login',
133 body: {
134 username: 'valid',
135 password: 'valid',
136 },
137 session: {},
138 });
139
140 await login(ctx);
141
142 expect(ctx.session.user).toMatchObject({
143 username: 'valid',
144 accessToken: 'dummy-access-token',
145 });
146 });
147});
148```
149
150### createMockCookies
151
152Creates a mock cookies instance.
153
154```javascript
155const cookies = createMockCookies({
156 sessionID: 'something something',
157 store: 'shop1',
158 referrer: 'somewhere.io',
159});
160```
161
162The returned object will have the signature
163
164```typescript
165interface MockCookies {
166 set(key: string, value: string): void;
167 get(key: string): string;
168 responseStore: Map<string, string>;
169 requestStore: Map<string, string>;
170}
171```
172
173The `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`.
174
175```javascript
176// will set to the response store
177cookies.set('key', 'value');
178
179// will get from the request store
180cookies.get('key') !== 'value';
181// => true
182```
183
184When 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.
185
186```javascript
187cookies.set('foo', 'bar');
188expect(cookies.set).toBeCalledWith('foo', 'bar');
189```
190
191```javascript
192cookies.set('foo', 'bar');
193expect(cookies.responseStore.get('foo')).toBe('bar');
194```