Skip to content

Instantly share code, notes, and snippets.

@kalouo
Last active December 3, 2020 08:09
Show Gist options
  • Save kalouo/b5a7482fe97c6cecd3aea2ced4b37e42 to your computer and use it in GitHub Desktop.
Save kalouo/b5a7482fe97c6cecd3aea2ced4b37e42 to your computer and use it in GitHub Desktop.
Tests With Mocks and Recordings
{
method: true,
headers: false,
body: true,
order: false,
url: {
protocol: false,
username: false,
password: false,
hostname: true,
port: false,
pathname: true,
query: true,
}
import { Polly } from '@pollyjs/core'
import FSPersister from '@pollyjs/persister-fs'
import NodeHttpAdapter from '@pollyjs/adapter-node-http'
import { setupPolly } from 'setup-polly-jest'
Polly.register(NodeHttpAdapter)
Polly.register(FSPersister)
export const start = () => {
setupPolly({
mode: 'replay', /* Replay recordings if they exist */
adapters: [ 'node-http' ],
persister: 'fs',
persisterOptions: {
fs: { recordingsDir: 'foo/bar' } /* File path to persist recordings */
},
expiresIn: '30d', /* Recordings expire in 30 days */
expiryStrategy: 'warn', /* Console warning if a recording is expired. */
matchRequestsBy: {/* Your configuration here. See below */}
})
}
{
expiryStrategy: process.env.CI? 'warn' : 'record'
recordIfMissing: process.env.CI? false : true
}
describe('UserService', () => {
beforeEach(() => {
APICall = jest
.spyOn(APIService, 'get')
.mockImplementation(userId => { /* mock endpoint response here */ })
})
test('should format successful response correctly, async () => {
const actual = await UserService.getUserInfo("@helvantine")
const expected = { /* Define formatted response here. */}
expect(actual).toStrictEqual(expected)
})
})
import * as Polly from './polly'
/* ... */
describe('UserService', () => {
Polly.start()
test('should format successful response correctly, async () => {
const actual = await UserService.getUserInfo("@helvantine")
const expected = { /* Define formatted response here. */}
expect(actual).toStrictEqual(expected)
})
})
class UserService {
public getUserInfo = async (id) => {
const response = await APIService.get(`/user?id=${id}`)
return this.formatResponse(response)
}
private formatResponse = (response) => {
/* Formatting logic here */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment