Skip to content

Commit

Permalink
feat(test-utils)!: improvements in createMock parameters and added su…
Browse files Browse the repository at this point in the history
…pport for json fixtures
  • Loading branch information
rudemex committed Nov 17, 2023
1 parent 936901c commit 0d31c78
Show file tree
Hide file tree
Showing 4 changed files with 170 additions and 56 deletions.
6 changes: 4 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "tsconfig.json",
"project": "<tsconfigRootDir>/**/*/tsconfig.json",
"sourceType": "module",
"createDefaultProgram": true
},
Expand All @@ -19,6 +19,7 @@
],
"root": true,
"env": {
"es2020": true,
"node": true,
"jest": true
},
Expand All @@ -30,6 +31,7 @@
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-unused-vars": "off"
"@typescript-eslint/no-unused-vars": "off",
"prefer-const": "off"
}
}
75 changes: 72 additions & 3 deletions packages/test-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,8 @@ describe('MyController', () => {
//...
it('should be return user data from mock', async () => {
createMock({
baseUrl: 'https://test.com',
url: 'https://test.com/api/user/1',
method: 'get',
endpoint: '/api/user/1',
statusCode: 200,
responseBody: {
id: 1,
Expand All @@ -153,7 +152,6 @@ describe('MyController', () => {
email: 'john.doe@email.com',
},
});

const user = await controller.getUser();
//console.log(user); //Return mock response
expect(user).toHaveProperty('firstName', 'John');
Expand All @@ -164,6 +162,77 @@ describe('MyController', () => {
});
```

El `responseBody` del `createMock` admite también otros tipos de respuesta además de `JSON`.

#### Response body as JSON

```typescript
createMock({
url: 'http://example.com/api/data',
method: 'get',
statusCode: 200,
responseBody: { success: true },
});
```

#### Response body as string

```typescript
createMock({
url: 'http://example.com/api/message',
method: 'get',
statusCode: 200,
responseBody: 'Success message',
});
```

#### Response body as Buffer

```typescript
createMock({
url: 'http://example.com/api/file',
method: 'get',
statusCode: 200,
responseBody: Buffer.from('Some binary data'),
});
```

#### Response body as function

Esta funcionalidad es ideal para tener fixtures de respuestas en archivos json y retornarlos.

```typescript
createMock({
url: 'http://example.com/api/dynamicData',
method: 'get',
statusCode: 200,
responseBody: () =>
JSON.parse(fs.readFileSync(path.resolve(__dirname, '../path/to/fixture.json'), 'utf8')),
});
```

En el caso de que tengas muchos fixtures y asi evitar duplicidad de código, pódes abstraer la función que retorna el `JSON`
con el siguiente código.

```typescript
const readFixtureFile = (filePath: string) => {
const absolutePath = path.resolve(__dirname, filePath);
const fileContents = fs.readFileSync(absolutePath, 'utf8');
return JSON.parse(fileContents);
};
```

y luego pódes utilizarlo de la siguiente manera, ya que la respuesta es un `JSON`.

```typescript
createMock({
url: 'http://example.com/api/dynamicData',
method: 'get',
statusCode: 200,
responseBody: readFixtureFile('../path/to/fixture.json'),
});
```

<a name="testcontainers"></a>

## 🧪 TestContainers
Expand Down
51 changes: 31 additions & 20 deletions packages/test-utils/src/__test__/createMock.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,21 @@ describe('createMock', () => {

it('should mock a GET request', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'get',
endpoint: '/api',
statusCode: 200,
responseBody: { success: true },
});

const res = await axios.get('http://test.com/api');
expect(res.status).toBe(200);
expect(res.data).toEqual({ success: true });
});

it('should mock a POST request with body', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'post',
endpoint: '/api',
statusCode: 201,
responseBody: { success: true },
reqBody: { key: 'value' },
Expand All @@ -36,78 +35,89 @@ describe('createMock', () => {

it('should mock a PUT request with body', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'put',
endpoint: '/api',
statusCode: 200,
responseBody: { success: true },
reqBody: { key: 'updatedValue' },
});

const res = await axios.put('http://test.com/api', { key: 'updatedValue' });
expect(res.status).toBe(200);
expect(res.data).toEqual({ success: true });
});

it('should mock a PATCH request with body', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'patch',
endpoint: '/api',
statusCode: 200,
responseBody: { success: true },
reqBody: { key: 'updatedValue' },
});

const res = await axios.patch('http://test.com/api', { key: 'updatedValue' });
expect(res.status).toBe(200);
expect(res.data).toEqual({ success: true });
});

it('should mock a DELETE request with body', async () => {
it('should mock a DELETE request', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'delete',
endpoint: '/api',
statusCode: 200,
responseBody: { success: true },
});

const res = await axios.delete('http://test.com/api');
expect(res.status).toBe(200);
expect(res.data).toEqual({ success: true });
});

it('should create a POST mock with the provided request body as Buffer', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/test-buffer',
method: 'post',
endpoint: '/test-buffer',
statusCode: 200,
responseBody: { success: true },
reqBody: Buffer.from('Hello, World!'),
responseBody: Buffer.from('Buffer Response'),
});

const res = await axios.post('http://test.com/test-buffer', Buffer.from('Hello, World!'));
expect(res.data).toEqual({ success: true });
expect(res.status).toBe(200);
expect(res.data).toEqual('Buffer Response');
});

it('should mock a request with function as responseBody', async () => {
createMock({
url: 'http://test.com/api/dynamicData',
method: 'get',
statusCode: 200,
responseBody: () => ({ dynamic: 'data' }),
});

const res = await axios.get('http://test.com/api/dynamicData');
expect(res.status).toBe(200);
expect(res.data).toEqual({ dynamic: 'data' });
});

it('should mock with query parameters', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'get',
endpoint: '/api',
statusCode: 200,
responseBody: { success: true },
queryParams: { key: 'value' },
});

const res = await axios.get('http://test.com/api', { params: { key: 'value' } });
expect(res.status).toBe(200);
expect(res.data).toEqual({ success: true });
});

it('should handle options with headers', async () => {
createMock({
baseUrl: 'http://test.com',
url: 'http://test.com/api',
method: 'get',
endpoint: '/api',
statusCode: 200,
responseBody: { success: true },
options: {
Expand All @@ -120,6 +130,7 @@ describe('createMock', () => {
const res = await axios.get('http://test.com/api', {
headers: { authorization: 'Bearer token' },
});
expect(res.status).toBe(200);
expect(res.data).toEqual({ success: true });
});
});
Loading

0 comments on commit 0d31c78

Please sign in to comment.