Giter Site home page Giter Site logo

jest-playback's People

Contributors

defrex avatar dependabot[bot] avatar greenkeeper[bot] avatar ikatyang avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jest-playback's Issues

Unique playback for each test

Thank you for this awesome project!

Having this makes the tests much more concise, which is lovely. I'm having an issue with running two requests which differ in request headers, which returns two different results. From what I can understand, jest-playback doesn't consider them to be two different requests.

AFAIK, we can add jest test names to make them unique per test.

Would you fancy a pull request on this?

Error importing jest-playback into my commonjs project

I'm trying to import jest-playback in a test, but I encounter the following error:

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/xxx/git/my-api/node_modules/jest-playback/lib/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { Mode } from './modes.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import xxx
    > 2 | import * as jestPlayback from 'jest-playback'

my tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2021",
    "module": "commonjs",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "strictPropertyInitialization": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "paths": {
      "@rootDir/*": ["./src/*"],
      "@controllers/*": ["./src/controllers/*"],
      "@routes/*": ["./src/routes/*"],
      "@utils/*": ["./src/utils/*"],
      "@services/*": ["./src/services/*"],
      "@settings/*": ["./src/settings/*"],
      "@interfaces/*": ["./src/interfaces/*"],
      "@providers/*": ["./src/providers/*"]
    }
  },
  "exclude": ["node_modules", "dist"]
}

my jest.config.js:

module.exports = {
  testEnvironment: 'jest-environment-node',
  verbose: true,
  setupFiles: ['./test/setup.js'],
  collectCoverageFrom: [
    'src/**/*.ts',
    '!dist/**/*',
    '!src/utils/index.ts',
    '!src/app.ts',
    '!src/index.ts',
    '!src/settings/*.ts'
  ],
  coveragePathIgnorePatterns: ['<rootDir>/src/swagger.ts'],
  testPathIgnorePatterns: ['/node_modules/', '/dist/'],
  moduleNameMapper: {
    '^@rootDir/(.*)$': '<rootDir>/src/$1',
    '^@controllers/(.*)$': '<rootDir>/src/controllers/$1',
    '^@routes/(.*)$': '<rootDir>/src/routes/$1',
    '^@utils/(.*)$': '<rootDir>/src/utils/$1',
    '^@services/(.*)$': '<rootDir>/src/services/$1',
    '^@settings/(.*)$': '<rootDir>/src/settings/$1',
    '^@providers/(.*)$': '<rootDir>/src/providers/$1'
  }
}

hash not computed correctly (use stringify on body)

  var hash = revHash(
    method +
      '+' +
      record.status +
      '+' +
      record.scope +
      '+' +
      record.path +
      '+' +
      JSON.stringify(record.body)
  );

you need the JSON.stringify(record.body) because body is an Object, not a string.
you might consider using https://github.com/substack/json-stable-stringify for extra resilience

a test case to show the problem is to have two post requests to the same endpoint but with different bodies, as:

{
  "scope": "https://engine-dev.diffeo.com:443",
  "method": "POST",
  "path": "/diffeo/diffeo/board/journal/search",
  "body": {
    "archived": false,
    "limit": null
  },
  "status": 200,
  "response": { }
} 

and:

{
  "scope": "https://engine-dev.diffeo.com:443",
  "method": "POST",
  "path": "/diffeo/diffeo/board/journal/search",
  "body": {
    "archived": true,
    "limit": null
  },
  "status": 200,
  "response": { }
} 

you'll witness that the HASH computed for both these requests is the same.

bound to test context

I would like to have this cool tool work in different modes in different tests. how can I do that?

Nock beta releases

Hi! We've started making beta releases toward the next major release of nock. Would you be up for giving one of them a shot in some tests for this library to help us ensure compatibility?

npm
npm@beta

Note that v11, when it's released, will drop support for Node 6.

Create new mode to record new requests only

It would be nice to have an additional record mode where new requests get recorded but existing playbacks get used if present. (maybe record-new ?)

The current record mode overwrites all existing data, which can sometimes be desirable but not always.

export `Mode` enum to allow smooth typescript usage

this is my current code:

import {setup as setupJestPlayback} from "jest-playback";
import {Mode} from "jest-playback/lib/mode"

setupJestPlayback(__dirname, Mode.Record);

please save me the 2nd impoort by exporting Mode from your index

Working with `axios-cookiejar-support` ?

I'm not able to get this working to 1) record requests and 2) play them back.

the test works perfectly fine if i comment out the await jestPlayback.setup({ ... }) line.

src.ts

import axios from 'axios'
import { wrapper } from 'axios-cookiejar-support';

wrapper(axios);

const data = (await axios.request({
  ...
})).data

test.ts

import * as jestPlayback from 'jest-playback';
await jestPlayback.setup({ mode: jestPlayback.Mode.Auto });

import * as src from './src'

// do tests

when i run the test in jest,

node --experimental-vm-modules node_modules/.bin/jest test.ts

 FAIL  test.test.ts
  test
    ✕  happy path (1364 ms)

  ● test ›  happy path

    AxiosError: Request failed with status code 401

      at settle (node_modules/axios/lib/core/settle.js:19:12)
      at PassThrough.handleStreamEnd (node_modules/axios/lib/adapters/http.js:589:11)

test.ts.snap

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`test happy path: (jest-playback) 86230859c6 1`] = `
NONE/11 401 Unauthorized
cf-cache-status: DYNAMIC
cf-ray: 8492d7c0ac274211-EWR
connection: keep-alive
content-type: text/html; charset=UTF-8
date: Sun, 21 Jan 2024 22:02:40 GMT
server: cloudflare
set-cookie: _cfuvid=2q37XoAAhzrdz.kcRy9F4Jjf6lAhpOxuqI92YqyvaMU-1705874560244-0-604800000; path=/; domain=.bamboohr.com; HttpOnly; Secure; SameSite=None
strict-transport-security: max-age=31536000; includeSubDomains; preload
transfer-encoding: chunked
x-frame-options: SAMEORIGIN
x-session-invalid: true
`;

Test suite passes, but process throws `AssertionError: playback not found`

file.test.ts

import * as jestPlayback from 'jest-playback'; 

await jestPlayback.setup({ mode: jestPlayback.Mode.Play });

...

execution:

$ npm test -- file.test.ts -u

> node --no-warnings --experimental-vm-modules node_modules/.bin/jest file.test.ts -u

{"level":"debug","time":"2024-01-23T07:16:46.303Z","msg":"making request"}
{"level":"debug","time":"2024-01-23T07:16:46.366Z","msg":"made request"}
 PASS  file.test.ts (6.144 s)
  test
    ✓ test happy path (77 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        6.171 s, estimated 8 s
Ran all test suites matching /file.test.ts/i.
AssertionError [ERR_ASSERTION]: playback not found
    at PlaybackManager.onRequest (/Users/skilbjo/dev/providers/node_modules/jest-playback/lib/manager.js:30:17)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /Users/skilbjo/dev/providers/node_modules/jest-playback/lib/setup.js:21:26
    at async queue.push.done (/Users/skilbjo/dev/providers/node_modules/@mswjs/interceptors/lib/node/chunk-Y5QA6OEZ.mjs:43:13)
@Johns-MacBook-Air:providers $ echo $?
1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.