Skip to content

Commit

Permalink
feat(Mocketeer): QA-20 allow to intercept requests of any type
Browse files Browse the repository at this point in the history
BREAKING CHANGE: remove deprecated API methods
BREAKING CHANGE: rename types
BREAKING CHANGE: can mock any requests, not just FETCH/XHR calls
  • Loading branch information
lukaszfiszer committed Oct 28, 2019
1 parent ad67834 commit 4d0a644
Show file tree
Hide file tree
Showing 17 changed files with 431 additions and 345 deletions.
62 changes: 23 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,21 @@ test('can create client', async () => {
const mocketeer = Mocketeer.setup(page);

// Set up a mock
const mock = await mocketeer.mockREST(
{
method: 'POST',
path: '/api/user',
const mock = await mocketeer.mockPost('/api/user', {
status: 201,
body: {
userId: '123',
},
{
status: 201,
body: {
userId: '123',
},
}
);
});

// Do something on the page
await page.type('.email', '[email protected]');
await page.click('.submit-button');

// Verify request content
await expect(mock.getRequest()).resolves.toMatchObject({
body: {
user_email: '[email protected]',
},
// Wait for mock to be called and verify request content
const request = await mock.getRequest();
expect(request.body).toEqual({
user_email: '[email protected]',
});
});
```
Expand All @@ -64,27 +57,22 @@ import { Mocketeer } from '@hltech/mocketeer';
const mocketeer = Mocketeer.setup(page);

// Set up a mock
const mock = await mocketeer.mockREST(
{
method: 'POST',
path: '/api/user',
const mock = await mocketeer.mockPost('/api/user', {
status: 201,
body: {
userId: '123',
},
{
status: 201,
body: {
error: false,
},
}
);
});

// Do something on the page
await page.type('.email', '[email protected]');
await page.click('.submit-button');

// Wait for mock to be called and verify request content
const req = await mock.getRequest();
console.log(req.method); // POST
console.log(req.body); // { user_email: "[email protected]" }
const request = await mock.getRequest();
expect(request.body).toEqual({
user_email: '[email protected]',
});
})();
```

Expand All @@ -96,7 +84,7 @@ import { Mocketeer } from '@hltech/mocketeer';

Factory method used to set-up request mocking on provided Puppeteer Page. It creates and returns an instance of Mocketeer

Mocketeer will intercept all requests made by the page and match them to mocks set up with `mocketeer.addRestMock`.
Mocketeer will intercept all requests made by the page and match them to mocks set up with `mocketeer.mock`.
If request does not match any mocks, it will be responded with `404 Not Found`.

###### Arguments
Expand All @@ -113,10 +101,6 @@ const page = await browser.newPage();
const mocketeer = await Mocketeer.setup(page);
```

#### ~~.activate(page: Page): Promise\<void\>~~ (depracated)

Activate mocketeer on a given page.

###### Arguments

- `page` _(Page)_ instance of Puppeteer [Page](https://pptr.dev/#?product=Puppeteer&show=api-class-page)
Expand All @@ -133,7 +117,7 @@ const page = await browser.newPage();
await mocketeer.activate(page);
```

#### .mockREST(filter: RequestFilter, response: MockedResponse, options?): RestMock
#### .mock(filter: RequestFilter, response: MockedResponse, options?): RestMock

Respond to xhr and fetch requests that match the `filter` with provided `response`.
Request are matched based on adding order - most recently added first.
Expand Down Expand Up @@ -161,7 +145,7 @@ Newly created instance of `RestMock`.
###### Example

```typescript
mocketeer.mockREST(
mocketeer.mock(
{
method: 'POST',
url: '/api/clients',
Expand All @@ -178,7 +162,7 @@ mocketeer.mockREST(
###### Example with query passed as an argument

```typescript
mocketeer.mockREST(
mocketeer.mock(
{
method: 'GET',
url: '/api/clients',
Expand All @@ -199,7 +183,7 @@ mocketeer.mockREST(
###### Example with queryString appended to the url

```typescript
mocketeer.mockREST(
mocketeer.mock(
{
method: 'GET',
url: '/api/clients?city=Bristol&limit=10',
Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ module.exports = {
tsConfig: 'test/integration/tsconfig.json',
},
},
resetMocks: true,
restoreMocks: true,
},
],
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"puppeteer": "1.13",
"semantic-release": "^15.13.3",
"ts-jest": "^24.0.1",
"typescript": "^3.4.1"
"typescript": "^3.6.3"
},
"files": [
"dist"
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './mocketeer';
export * from './rest-mock';
export * from './mock';
export * from './types';
39 changes: 18 additions & 21 deletions src/rest-mock.ts → src/mock.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ResourceType } from 'puppeteer';
import dbg from 'debug';
import {
IMock,
Expand All @@ -9,7 +8,7 @@ import {
PathParameters,
QueryObject,
ReceivedRequest,
RequestFilter,
RequestMatcherObject,
} from './types';
import { waitFor, TimeoutError, nth, arePathsDifferent } from './utils';
import isEqual from 'lodash.isequal';
Expand All @@ -23,7 +22,7 @@ const GET_REQUEST_TIMEOUT = 100;

let debugId = 1;

export class RestMock implements IMock {
export class Mock implements IMock {
private filter: ParsedFilterRequest;
private response: MockedResponse;
private requests: Array<MatchedRequest> = [];
Expand All @@ -36,7 +35,7 @@ export class RestMock implements IMock {
private paramNames: (string | number)[] = [];

constructor(
filter: RequestFilter,
filter: RequestMatcherObject,
response: MockedResponse,
options: Partial<MockOptions> = {}
) {
Expand Down Expand Up @@ -103,31 +102,29 @@ export class RestMock implements IMock {
}

this.requests.push({ ...request, params: this.getParams(request) });

const headers = {
...{ 'Content-Type': 'application/json' },
...this.response.headers,
};

const body =
headers['Content-Type'] === 'application/json'
? JSON.stringify(this.response.body)
: this.response.body;

return {
status: this.response.status,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.response.body),
headers,
body,
};
}

private static allowedTypes: ResourceType[] = ['fetch', 'xhr'];

private isMatchingRequest(
request: ReceivedRequest,
pageOrigin: string
): boolean {
if (RestMock.allowedTypes.indexOf(request.type) === -1) {
this.debugMiss(
'type',
request.type,
RestMock.allowedTypes.toString()
);
return false;
}

if (request.method !== this.filter.method) {
if (this.filter.method && request.method !== this.filter.method) {
this.debugMiss('method', request.method, this.filter.method);
return false;
}
Expand Down Expand Up @@ -167,7 +164,7 @@ export class RestMock implements IMock {
}

private createParsedFilterRequest(
filter: RequestFilter
filter: RequestMatcherObject
): ParsedFilterRequest {
// TODO find a better alternative for url.parse
const { protocol, host, pathname, query } = parse(filter.url, true);
Expand Down
Loading

0 comments on commit 4d0a644

Please sign in to comment.