Skip to content

Commit

Permalink
Merge pull request #10 from Tabueeee/v-1.3.0
Browse files Browse the repository at this point in the history
v-1.3.0: Interfaces and isMatchingRequest for more flexibility
  • Loading branch information
Tabueeee authored Jan 20, 2019
2 parents a1a3a68 + be3c2ef commit 15ad6c1
Show file tree
Hide file tree
Showing 55 changed files with 737 additions and 166 deletions.
2 changes: 2 additions & 0 deletions .idea/puppeteer-request-spy.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ examples/
src/
build/test/
test/
task/
tsconfig.json
tsconfig-lint.json
tslint.json
Expand All @@ -125,3 +126,4 @@ build/**/*.js.map
custom-typings/
.travis.yml
.coveralls.yml
CONTRIBUTING.md
18 changes: 18 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
This Project uses Semantic Versioning. More information can be found [here](https://semver.org/).

The branch and tag names also follow the following convention:
- branches: ```v-x.y.z```
- tags: ```vx.y.z```

You only need to follow this convention when creating a Pull Request for a full npm release.

Please make sure your branch passes the build process by running ```npm test```.
You can check the code coverage by generating a html report using ```npm run test-coverage```.

The tslint setting may seem harsh but they are usually useful to determine problems.
Try to fix as much as possible but I am not contempt on keeping every rule.
Some are a matter of choice after all.

If you want to ensure a proper release, bump the version in the package.json and run ```npm run release-dry```.
This will run all required steps for a successful release like ts-lint, build, test, generating types
and creates a preview of the final package pushed to npm.
63 changes: 49 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,11 @@ for (let matchedRequest of cssSpy.getMatchedRequests()) {
## API

### class: RequestInterceptor
The `RequestInterceptor` will match any intercepted request against the `matcher` function and notify all spies with a matching pattern and block requests matching any pattern in `urlsToBlock`.
The `RequestInterceptor` will call all spies, fakers and blocker to dertermine if an intercepted request matches. against the `matcher` function and notify all spies with a matching pattern and block requests matching any pattern in `urlsToBlock`.

#### RequestInterceptor constructor(matcher, logger?)
- `matcher`: <(url: string, pattern: string) => boolean>>
- `logger?`: <{log: (text: string) => void}>
- `matcher`: \<(url: string, pattern: string) =\> boolean\>\>
- `logger?`: \<{log: (text: string) =\> void}\>

The `matcher` will be called for every url, testing the url against patterns of any `RequestSpy` provided and also any url added to `urlsToBlock`.

Expand All @@ -118,17 +119,17 @@ The `logger` if provided will output any requested url with a 'loaded' or 'abort
Function to be registered with puppeteer's request event.

#### RequestInterceptor.addSpy(requestSpy)
- requestSpy: \<RequestSpy> spy to register
- requestSpy: \<IRequestSpy> spy to register

Register a spy with the `RequestInterceptor`.

#### RequestInterceptor.clearSpies()
Clears all registered spies.

#### RequestInterceptor.addFaker(requestFaker)
- responseFaker: \<ResponseFaker> faker to register
- responseFaker: \<IResponseFaker> faker to register

#### RequestInterceptor.clearFakers()
#### RequestInterceptor.clearFakers()
Clears all registered fakers.

#### RequestInterceptor.block(urlsToBlock)
Expand All @@ -142,7 +143,12 @@ Clears all registered fakers.
#### RequestInterceptor.clearUrlsToBlock()
Clears all registered patterns in `urlsToBlock`.

### class: RequestSpy
#### RequestInterceptor.setRequestBlocker(requestBlocker)
- requestBlocker \<IRequestBlocker\>

Allows you to replace the default RequestBlocker by your own implementation.

### class: RequestSpy implements IRequestSpy
`RequestSpy` is used to count and verify intercepted requests matching a specific pattern.
#### RequestSpy constructor(pattern)
- `pattern`: \<string|Array\<string>>
Expand All @@ -161,28 +167,57 @@ Clears all registered patterns in `urlsToBlock`.
#### RequestSpy.getMatchCount()
- returns: \<number> number of urls that matched the `pattern`

#### RequestSpy.getPatterns()
- returns: \<Array\<string\>\> return the `pattern` list of the spy
#### RequestSpy.isMatchingRequest(request, matcher)
- request \<Request\> request object provided by puppeteer
- matcher \<(url: string, pattern: string) =\> boolean\>\> matching function passed to RequestInterceptor's constructor
- returns: \<boolean\> returns true if any pattern provided to the RequestSpy matches the request url

The `RequestInterceptor` calls this method to determine if an interceptedRequest matches the RequestSpy.

#### RequestSpy.addMatch(matchedRequest)
- matchedRequest: \<Request> request that was matched

The `RequestInterceptor` calls this method when an interceptedRequest matches the pattern.

### class: RequestFaker
`RequestFaker` is used to provide a fake response when matched to a specific pattern.
### class: ResponseFaker implements IResponseFaker
`ResponseFaker` is used to provide a fake response when matched to a specific pattern.

#### RequestFaker constructor(pattern, responseFake)
#### ResponseFaker constructor(pattern, responseFake)
- `pattern`: \<string|Array<string>>
- `responseFake`: \<`Response`> for details refer to [puppeteer API](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#requestrespondresponse)

#### RequestFaker.getPatterns()
#### ResponseFaker.getPatterns()
- returns: \<Array\<string\>\> return the `pattern` list of the faker

#### RequestFaker.getResponseFake()
#### ResponseFaker.getResponseFake()
- returns: \<Response\> return the fake response

The `RequestInterceptor` calls this method when an interceptedUrl matches the pattern.

#### ResponseFaker.isMatchingRequest(request, matcher)
- request \<Request\> request object provided by puppeteer
- matcher \<(url: string, pattern: string) =\> boolean\>\> matching function passed to RequestInterceptor's constructor
- returns: \<boolean\> returns true if any pattern provided to the ResponseFaker matches the request url

The `RequestInterceptor` calls this method to determine if an interceptedRequest matches.

### class: RequestBlocker implements IResponseBlocker
`RequestBlocker` is used to by the RequestInterceptor to match requests to block.

#### RequestBlocker.shouldBlockRequest(request, matcher)
- request \<Request\> request object provided by puppeteer
- matcher \<(url: string, pattern: string) =\> boolean\>\> matching function passed to RequestInterceptor's constructor

The `RequestInterceptor` calls this method to determine if an interceptedRequest matches.

#### RequestBlocker.addUrlsToBlock(urls)
- urls \<Array<string> | string\>

Adds new urls to the block list.

#### RequestBlocker.clearUrlsToBlock()

Removes all entries of the block list.

# Examples

Expand Down
35 changes: 35 additions & 0 deletions examples/CustomFaker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {Request} from 'puppeteer';
import {RespondOptions} from 'puppeteer';
import {IResponseFaker, RequestMatcher} from 'puppeteer-request-spy';

export class CustomFaker implements IResponseFaker {

private patterns: Array<string> = [];
private fakesMap = {
'GET': 'some text',
'POST': 'Not Found!'
};

public constructor(patterns: Array<string>) {
this.patterns = patterns;
}

public getResponseFake(request: Request): RespondOptions {
return {
status: 200,
contentType: 'text/plain',
body: this.fakesMap[request.method()]
};
}

public isMatchingRequest(request: Request, matcher: RequestMatcher): boolean {
for (let pattern of this.patterns) {
if(matcher(request.url(), pattern)){

return true;
}
}

return false;
}
}
27 changes: 27 additions & 0 deletions examples/CustomSpy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {IRequestSpy, RequestMatcher} from 'puppeteer-request-spy';
import {Request, Response} from 'puppeteer';
import * as assert from "assert";


export class CustomSpy implements IRequestSpy {
private matches: Array<Request> = [];

public isMatchingRequest(request: Request, matcher: RequestMatcher): boolean {

return matcher(request.url(), '**/*');
}

public addMatch(matchedRequest: Request): void {

this.matches.push(matchedRequest);
}

public assertRequestsOk() {
for (let match of this.matches) {
let response: Response | null = match.response();
if (response !== null) {
assert.ok(response.ok());
}
}
}
}
19 changes: 15 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
{
"name": "puppeteer-request-spy",
"version": "1.2.0",
"version": "1.3.0",
"description": "watch, fake or block requests from puppeteer matching patterns",
"main": "build/src/index.js",
"scripts": {
"clean": "node task/clean.js",
"pregenerate-typings": "npm run clean",
"generate-typings": "tsc -p tsconfig.json -d",
"prebuild": "node_modules/.bin/tslint --project tsconfig-lint.json",
"preupdate-typings": "npm run generate-typings",
"update-typings": "node task/copyTypes.js",
"prebuild": "node_modules/.bin/tslint --project tsconfig-lint.json && npm run clean",
"prebuild-dev": "npm run prebuild",
"build": "node_modules/.bin/tsc -p tsconfig.json",
"build-dev": "node_modules/.bin/tsc -p tsconfig.json --sourcemap",
"pretest": "npm run build",
"test": "node_modules/.bin/mocha --timeout 10000 --require source-map-support/register build/test/**/*.spec.js",
"pretest-coverage": "npm run build-dev",
"pretest-silent-full": "npm run build",
"test-silent-full": "node_modules/.bin/mocha --timeout 10000 --require source-map-support/register build/test/**/*.spec.js > test-ts.log",
"test-coverage": "node_modules/.bin/nyc --all --reporter=html npm run test-silent",
"pretest-coverage-travis": "npm run build-dev",
"test-silent": "node_modules/.bin/mocha --timeout 10000 --require source-map-support/register build/test/**/*.dev.spec.js > test-ts.log",
"test-coverage-travis": "node_modules/.bin/nyc --all --reporter=text-lcov npm run test-silent | node node_modules/coveralls/bin/coveralls.js"
"test-coverage-travis": "node_modules/.bin/nyc --all --reporter=text-lcov npm run test-silent | node node_modules/coveralls/bin/coveralls.js",
"prerelease-dry": "npm run update-typings && npm run test-silent-full",
"release-dry": "npm pack"
},
"engines": {
"node": ">=6.4.0"
Expand All @@ -31,7 +38,8 @@
],
"exclude": [
"**/Logger.js",
"**/index.js"
"**/index.js",
"**/interface/*.js"
],
"reporter": [
"html"
Expand All @@ -51,13 +59,16 @@
"author": "Tobias Nießen",
"license": "MIT",
"devDependencies": {
"@types/fs-extra": "^5.0.4",
"@types/minimatch": "^3.0.3",
"@types/mocha": "^5.2.0",
"@types/node": "^10.0.4",
"@types/puppeteer": "^1.3.1",
"@types/sinon": "^4.3.1",
"clear-module": "^3.1.0",
"coveralls": "^3.0.1",
"del": "^3.0.0",
"fs-extra": "^7.0.1",
"minimatch": "^3.0.4",
"mocha": "^5.1.1",
"nyc": "^11.7.1",
Expand Down
30 changes: 30 additions & 0 deletions src/RequestBlocker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {Request} from 'puppeteer';
import {UrlAccessor} from './common/urlAccessor/UrlAccessor';
import {UrlAccessorResolver} from './common/urlAccessor/UrlAccessorResolver';
import {IRequestBlocker} from './interface/IRequestBlocker';
import {RequestMatcher} from './interface/RequestMatcher';

export class RequestBlocker implements IRequestBlocker {

private urlsToBlock: Array<string> = [];

public shouldBlockRequest(request: Request, matcher: RequestMatcher): boolean {
let urlAccessor: UrlAccessor = UrlAccessorResolver.getUrlAccessor(request);

for (let urlToBlock of this.urlsToBlock) {
if (matcher(urlAccessor.getUrlFromRequest(request), urlToBlock)) {
return true;
}
}

return false;
}

public addUrlsToBlock(urls: Array<string> | string): void {
this.urlsToBlock = this.urlsToBlock.concat(urls);
}

public clearUrlsToBlock(): void {
this.urlsToBlock = [];
}
}
Loading

0 comments on commit 15ad6c1

Please sign in to comment.