Search…
Mocking
This library provides helpers to set up API mocking in Node.JS and browser projects.

Quick Start

1
import {
2
factory,
3
createStore,
4
createResolvers,
5
createGraphqlHandler,
6
startMocking,
7
slugify,
8
faker,
9
} from '@island.is/shared/mocking'
10
import schema from './schema'
11
import { Article, User, Resolvers } from './types'
12
13
const user = factory<User>({
14
name: () => faker.name.findName(),
15
})
16
17
const article = factory<Article>({
18
title: () => faker.lorem.words(),
19
slug: slugify('title'),
20
author: () => user(),
21
})
22
23
const store = createStore(() => {
24
return {
25
articles: article.list(100),
26
}
27
})
28
29
const resolvers = createResolvers<Resolvers>({
30
Query: {
31
articles: (_obj, args) => {
32
const page = args.page || 0
33
const perPage = args.perPage || 10
34
const start = page * perPage
35
return store.articles.slice(start, start + perPage)
36
},
37
},
38
})
39
40
if (process.env.NODE_ENV !== 'production' && process.env.API_MOCKS) {
41
startMocking([createGraphqlHandler({ schema, resolvers })])
42
}
Copied!
We recommend generating the schema and types from the real api using GraphQL Code Generator. Something like this:
schema.ts
1
import { buildSchema } from 'graphql'
2
3
// This should be pulled directly from the real api.
4
export default buildSchema(`
5
type User {
6
name: String!
7
}
8
9
type Article {
10
title: String!
11
slug: Slug!
12
author: User!
13
}
14
15
type Query {
16
articles(page: Number, perPage: Number): Article[]!
17
}
18
`)
Copied!
types.ts
1
export interface User {
2
name: string
3
}
4
5
export interface Article {
6
title: string
7
slug: string
8
author: User
9
}
10
11
export interface Resolvers {
12
User?: {
13
name?: () => string
14
}
15
Article?: {
16
title?: () => string
17
slug?: () => string
18
author?: () => User
19
}
20
Query?: {
21
articles?: (
22
obj: any,
23
input: { page?: number; perPage?: number },
24
) => Article[]
25
}
26
}
Copied!

Functions

startMocking(requestHandlers)

Starts Mock Service Worker (MSW) with the specified MSW requestHandlers.
For this to work in browsers, you need to add mockServiceWorker.js to your public folder by running yarn msw init path/to/your/public/. Automatically works in Node.JS.
Note: Should only be called in development when mocking is turned on.

Arguments

  • requestHandlers: Array<msw.RequestHandler> - a list of mocked request handlers. Can use standard MSW rest/graphql handlers. We recommend using strongly typed GraphQL mocks using createGraphqlHandler below.

Returns

msw.SetupWorkerApi | msw.SetupServerApi
The return object can be used to add or override requestHandlers with mocking.use(...requestHandlers). These can be reset with mocking.resetHandlers().

Usage

1
import { startMocking, createGraphqlHandler } from '@island.is/shared/mocking'
2
import { rest } from 'msw'
3
import resolvers from './resolvers'
4
import schema from './schema'
5
6
if (process.env.NODE_ENV !== 'production' && process.env.API_MOCKS) {
7
startMocking([
8
rest.post('/login', (req, res, ctx) => {
9
const { username } = req.body
10
return res(
11
ctx.json({
12
username,
13
firstName: 'John',
14
}),
15
)
16
}),
17
createGraphqlHandler({ resolvers, schema }),
18
])
19
}
Copied!

createGraphqlHandler(options: Options)

Creates an MSW request handler which evaluates graphql requests using a schema and resolvers.
The reason we use this handler instead of the built in MSW graphql handlers is that it can share the same schema as the real API and use strongly typed resolvers.
This provides better developer experience when mocking resolvers and creating test data, and allows the CI to catch instances where mocks are out of date.

Arguments

  • Options#mask?: string | RegExp - which urls to handle. Defaults to '*/api/graphql'.
  • resolvers: Resolvers - graphql resolvers as returned by createResolvers below.
  • schema: GraphQLSchema - graphql schema for mock api.

Returns

  • msw.RequestHandler - should be passed to startMocking() above.

Calling real api's with fetch

MSW provides a special fetch function that ignores its mocking handlers. The graphql handler passes this fetch function to resolvers using the GraphQL context argument. Example:
1
createGraphqlHandler({
2
resolvers: createResolvers({
3
Query: {
4
hello: (_obj, _arg, context) => {
5
context.fetch('...')
6
},
7
},
8
}),
9
})
Copied!

createResolvers(baseResolvers)

Wraps a object with mocked graphql resolvers so it can be passed to createGraphqlHandler. Supports standard field and type resolvers.
The resolvers type should be generated with the TypeScript Resolvers plugin in GraphQL Code Generator for everything to be strongly typed.
Depending on the schema and application, it's not necessary to fully implement all resolvers. Any field (including queries and mutations) which does not have a resolver, returns null.

Arguments

  • baseResolvers: Resolvers - the initial mocked resolvers.

Returns

An object with the following methods:
  • #add(resolvers: Resolvers) - adds (and overrides) mocked resolvers. Useful to test edge cases in E2E test.
  • #reset() - resets resolvers to the initial resolvers passed to createResolvers()

Usage

1
import { createResolvers } from '@island.is/shared/mocking'
2
import { Resolvers } from './types'
3
4
const resolvers = createResolvers<Resolvers>({
5
Query: {
6
helloWorld: () => 'Hello World',
7
me: () => ({ firstName: 'John', lastName: 'Doe' }),
8
},
9
Mutation: {
10
setLanguage: () => {},
11
},
12
User: {
13
fullName: (user) => `${user.firstName} ${user.lastName}`,
14
},
15
UnionType: {
16
__resolveType: (obj) => obj.type,
17
},
18
})
Copied!

createStore<Data>(initializer)

Creates a store containing mocked data which can be used by mock handlers, resolvers and tests.
The store is created lazily, on demand, to not create a lot of mocking data until it's needed.
The store data can be freely edited (as plain JS objects), which is quite useful:
  • Mutations and write handlers can edit the store for later queries.
  • Tests can prepare special data for queries.
The store can also be reset to its initial state, e.g. in jest's afterEach().

Arguments

  • initializer: () => Data - a function which creates the mock data and returns as an object.

Returns

Short answer: The object returned by the initalizer function, with one additional property:
  • $reset(): void - Resets the store to the initial state.
Long answer: A Proxy object. Most properties are forwarded to the object returned by the initializer function. The initializer function is lazily invoked the first time a property is accessed.

Usage

1
import { createStore } from '@island.is/shared/mocking'
2
import { article } from './factories'
3
4
const store = createStore(() => ({
5
articles: article.list(100),
6
// ...
7
}))
8
9
console.log(store.articles.length) // 100
10
store.articles = []
11
console.log(store.articles.length) // 0
12
store.$reset()
13
console.log(store.articles.length) // 100
Copied!

factory<Type>(initializer)

Creates an object factory which can be used to create one or more objects using a strongly typed initializer and traits.
The Type generic can be specified explicitly based on types from the GraphQL schema to give a better developer experience.

Arguments

  • initializer - initializer object which matches the shape of Type.
Each property can have a static value (same for all created objects) or a function (dynamic value for each created object).
Dynamic properties can depend on other properties. The factory calls the property function with an object that contains all of the properties that have been assigned at that point. The object is passed both as this and as the first parameter.
1
factory({
2
a: 5,
3
b: (obj) => obj.a + 1,
4
})
Copied!
  • initializer.$traits - map of traits which can be used when generating objects.
Traits can be specified at creation time to modify the created object. Each trait has a name (the key) and an object containing new values for the created object, either static or dynamic.
1
factory({
2
a: 5,
3
$traits: {
4
large: {
5
a: 1000,
6
},
7
},
8
})
Copied!
Note: Properties are assigned in the order they are defined in the root initializer object (even if traits or overrides have another order). Example:
1
factory({
2
a: 5,
3
b() {
4
return this.a
5
},
6
c() {
7
return this.b
8
},
9
10
$traits: {
11
changed: {
12
c: 7,
13
// b will always return undefined since c is assigned after b.
14
b() {
15
return this.c
16
},
17
},
18
},
19
})
Copied!

Returns

A callable factory object.
(...data: Array<string | object>) => Type
Create a new object according to the factory schema. The function accepts an optional list of traits to use and/or an object that overrides properties.
#list(count: number, ...data: Array<string | object>) => Array<Type>
Create a list of count objects. Supports traits and overrides.

Usage

1
import { factory, faker } from '@island.is/shared/mocking'
2
import { User, Article } from './types'
3
4
const user = factory<User>({
5
name: () => faker.name.findName(),
6
})
7
8
const article = factory<Article>({
9
title: () => faker.lorem.words(),
10
body: () => faker.lorem.paragraphs(),
11
author: null,
12
13
$traits: {
14
withAuthor: {
15
author: () => user(),
16
},
17
long: {
18
body: () => faker.lorem.paragraphs(20),
19
},
20
},
21
})
22
23
// Elsewhere:
24
const normalArticle = article()
25
const primaryArticle = article('withAuthor', {
26
title: 'Hello World',
27
body: 'Welcome to the site',
28
})
29
const articles = article.list(3, 'withAuthor') // [Article, Article, Article]
Copied!

Other helpers

  • title()
Returns a title-like string using faker.lorem.words().
1
import { factory, title } from '@island.is/shared/mocking'
2
factory({
3
title: () => title(),
4
})
Copied!
  • slugify(field)
A helper to create slugged fields in factories:
1
import { factory, title, slugify } from '@island.is/shared/mocking'
2
factory({
3
title: () => title(),
4
slug: slugify('title'),
5
})
Copied!
  • simpleFactory(initializerFn)
Wraps a normal factory function and provides a #list helper to run it multiple times. All arguments are passed directly through. Appropriate for factories which create values which don't have a simple object schema (e.g. GraphQL union types).
1
import { simpleFactory } from '@island.is/shared/mocking'
2
const slice = simpleFactory(() =>
3
Math.random() > 0.5 ? contentSlice() : imageSlice(),
4
)
5
slice() // ContentSlice | ImageSlice
6
slice.list(3) // Array<ContentSlice | ImageSlice>
Copied!
  • faker
Re-exported faker to create fake mock data. One day we may add our own locale to create more Icelandic mock data.

Remove mocking code from production builds

The first step is to only call startMocking when process.env.API_MOCKS === 'true'. Then Webpack is able to remove it from the bundle in production builds.
However, that still leaves all the resolver, handler, store and factory code. Webpack doesn't remove that because the code looks like this:
1
const store = createStore(/* ... */)
Copied!
Webpack knows that store is not used in production builds, but it won't remove the code since createStore could have some side-effect.
We can tell Webpack that there are no side effects in this code, by creating a package.json in the mocking folder that includes { sideEffects: false }. However, that would remove the startMocking() call, which is a side effect we want (at least in development).
The fix is to keep startMocking in its own file (e.g. mocks/index.ts) and mark that as the only file with side effects:
1
{
2
"sideEffects": ["mocks/index.ts"]
3
}
Copied!
Last modified 10mo ago