UNPKG

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