Code Monkey home page Code Monkey logo

pptr-mock-server's Introduction

NPM downloads CI Coverage Status Renovate FOSSA Status

pptr-mock-server

Tiny library for backendless testing using Puppeteer.

Intro

This library allows to define mock backend responses when testing web app with Puppeteer.

Internally it works purely via Puppeteer API using built-in setRequestInterception mechanism. It doesn't set up any servers and doesn't modify any window APIs like XMLHttpRequest. This provides great flexibility and performance when handling requests, since it operates on browser internal level.

Recommended reading: Automated UI Testing at Dock.

Installing

yarn add -D pptr-mock-server

Setting up

import puppeteer from 'puppeteer'
import mockServer from 'pptr-mock-server'

// typically your global test setup
const browser = await puppeteer.launch()
const page = await browser.newPage()
const baseAppUrl = 'http://localhost'
const mockRequest = await mockServer.init(page, {
  baseAppUrl,
  baseApiUrl: baseAppUrl + '/api/'
})

Basic usage

Once you have an instance of MockRequest you can pass it to your tests for registering mock responses:

const responseConfig = { body: { result: 'ok' } }
mockRequest.on('get', 'http://localhost/api/account', 200, responseConfig)

But since you provided baseApiUrl as http://localhost/api, you can use relative endpoint name. Also you can use .get() shorthand method instead of .on():

const responseConfig = { body: { result: 'ok' } }
mockRequest.get('account', 200, responseConfig)

When your app performs request to the specified resource, it will respond with the mock response provided.

Common scenarios

Handle request to relative endpoint using .on method:

const responseConfig = { body: { result: 'ok' } }
mockRequest.on('get', 'account', 200, responseConfig)

Using shortcut .get method and absolute url:

const responseConfig = { body: { result: 'not found' } }
mockRequest.get('https://example.com/test', 404, responseConfig)

Simulate request timeout:

mockRequest.post('search', null, { abort: 'timedout', delay: 10000 })

Mocking sequence of identical requests

Once you setup a mock request handler, every matching request will be responded with it. However it's a common scenario when you need to mock a sequence of requests, when over time the same request produces different results. Recommended way to do it is to replace previously registered mock response using new one:

const responseConfig = { body: { result: 'ok' } }
mockRequest.get('account', 200, responseConfig) // returns 200 on each request
// test deleting account logic here
// after account is deleted we want to return 401 instead of 200
mockRequest.get('account', 401) // replaces existing handler

License

FOSSA Status

pptr-mock-server's People

Contributors

dependabot[bot] avatar ermakovich avatar fossabot avatar renovate-bot avatar renovate[bot] avatar soniahms 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

Watchers

 avatar  avatar

pptr-mock-server's Issues

Error: TypeError: mockServer.init is not a function

Hi,

I was trying to use your library to do the Puppeteer API mocking. But, I encountered this issue.
Any clue ? Thanks.

const mockServer = require('pptr-mock-server')

class Portal {
   async launchBrowser() {
     const baseAppUrl = 'https://cnc-api-dev.localz.io'
     this.mockRequest = await mockServer.init(this.page, {
        baseAppUrl,
        baseApiUrl: baseAppUrl + '/v1/api/'
     })

     const responseConfig = { body: {result: 'ok'} };
     this.mockRequest.get('api', 200, responseConfig);
   }
}
Error: TypeError: mockServer.init is not a function

This is the package version I'm using.
"pptr-mock-server": "^1.0.0"

Types

Looks like a nice API to mock response data with but there are no bundled .d.ts files. I see the type declarations in the source files but VS Code does not appear to find those in the distribution? Any tips?

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Pending Branch Automerge

These updates await pending status checks before automerging. Click on a checkbox to abort the branch automerge, and create a PR instead.

  • Update dependency @types/lodash to v4.17.3
  • Update dependency puppeteer to v22.9.0

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/node.js.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • chalk ^4.1.2
  • lodash ^4.17.15
  • @babel/cli 7.24.5
  • @babel/core 7.24.5
  • @babel/preset-env 7.24.5
  • @babel/preset-typescript 7.24.1
  • @tsconfig/node18 18.2.4
  • @types/lodash 4.17.1
  • coveralls 3.1.1
  • documentation 14.0.3
  • eslint 8.57.0
  • eslint-plugin-jest 28.5.0
  • jest 29.7.0
  • jest-junit 16.0.0
  • prettier 3.2.5
  • puppeteer 22.8.1
  • typescript 5.4.5
  • puppeteer >= 1.5
  • node >=18
nvm
.nvmrc
  • node 20.13.1

  • Check this box to trigger a request for Renovate to run again on this repository

Feature request: default to Ok

What are your thoughts on adding an option to default all requests not matching a mockRequest to Ok/continue?

In my use case, I'm doing visual diffing of screenshots, and I just want to mock a couple specific API calls per test, not the whole app.

I'm looking for something more like Cypress's fixture feature, and so far your API is the easiest to use for mocking Puppeteer requests.

Feature request: Promise/Async request response

It would be really nice if we could return a promise as the request response so we can control exactly when the request returns a response or an error.

e.g. I'm writing a unit test where the page makes a request, and I need the request to get a response only after I make some other action. I can get it working with the delay option, although that's not really reliable since I can't guarantee for sure that the action after the request will be finished before the delay ends.

How to mock loading Google Map API & support regex on the handler

Hi @ermakovich

1). Just wondering whether your library supports mocking the connection to Google Map API ?

this.mockRequest.on('GET', `https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${GOOGLE_MAP_API_KEY}`, 200, { body: {} })

Coz, I kept receiving this, even though I have provided valid GOOGLE_MAP_API_KEY

ReferenceError: google is not defined

2). Does the mockRequest handler supports regex on the API url ?

Eg.

this.mockRequest.on('GET', /^https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key/`, 200, { body: {} })

Thanks in advance,
Ferdinand

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.