Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nock + Jest (Auto save fixtures with nockback)
module.exports = {
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"setupTestFrameworkScriptFile": "<rootDir>/tests/setup.ts",
"testEnvironment": "node",
"testRegex": "(/__tests__/.*)\\.test\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
]
};

For exec test :

yarn test

Use NOCK_BACK_MODE env for change nock back mode

import * as nock from 'nock';
import { dirname, basename, join } from 'path';
import 'reflect-metadata';
/**
* get current test path
*/
function getTestPath(): string | undefined {
if (Symbol && typeof Symbol.for === 'function') {
const globalStateKey = Symbol.for('$$jest-matchers-object');
if (globalStateKey) {
const globalState = (<any>global)[globalStateKey];
if (globalState) {
const state = globalState.state;
if (state) {
return state.testPath;
}
}
}
}
}
interface NockBackValue {
nockDone: () => void;
context: nock.NockBackContext;
}
let value: NockBackValue | undefined;
let testPath: string | undefined;
let nb = 0;
beforeEach(async () => {
const newPath = getTestPath();
if (!newPath) {
return;
}
if (testPath !== newPath) {
testPath = newPath;
nb = 0;
} else {
nb++;
}
const nockBack = nock.back;
nockBack.fixtures = join(dirname(testPath), '__nocks__');
value = await nockBack(`${basename(testPath)}.${nb}.json`);
nock.enableNetConnect('127.0.0.1');
});
afterEach(async () => {
if (value) {
value.nockDone();
value = undefined;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.