Skip to content

Commit 561c2bd

Browse files
authored
feat(mongoose): addshooks for stubbing mongoose methods (#55)
* fix: stores correct http response for unique test-ids Signed-off-by: re-Tick <jain.ritik.1001@gmail.com> * feat(mongoose): adds hooks for mocking/stubbing mongoose methods Signed-off-by: re-Tick <jain.ritik.1001@gmail.com> * docs: updates the docs for mongoose and refactors Signed-off-by: re-Tick <jain.ritik.1001@gmail.com> * docs: refactors readme for e2e and mocks-lib docs Signed-off-by: re-Tick <jain.ritik.1001@gmail.com> * docs: adds require stmt in docs code snippet Signed-off-by: re-Tick <jain.ritik.1001@gmail.com> --------- Signed-off-by: re-Tick <jain.ritik.1001@gmail.com>
1 parent 10ff4eb commit 561c2bd

File tree

17 files changed

+4641
-3632
lines changed

17 files changed

+4641
-3632
lines changed

README.md

Lines changed: 165 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -3,86 +3,132 @@
33
[![License](.github/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
44

55
# Keploy Typescript-SDK
6-
[Keploy](https://keploy.io) is a no-code testing platform that generates tests from API calls. This is the Typescript client SDK for recording and replaying the API Calls. There are 2 modes:
7-
1. **Record mode**
8-
1. Record requests, response and sends to Keploy server.
9-
2. After keploy server removes duplicates, it then runs the request on the API again to identify noisy fields.
10-
3. Sends the noisy fields to the keploy server to be saved along with the testcase.
11-
2. **Test mode**
12-
1. Fetches testcases for the app from keploy server.
13-
2. Calls the API with same request payload in testcase.
14-
3. Validates the respones and uploads results to the keploy server.
6+
This is the client SDK for the [Keploy](https://github.com/keploy/keploy) testing platform. You can use this to generate realistic mock files or entire e2e tests for your applications. The **HTTP mocks/stubs and tests are the same format** and inter-exchangeable.
157

168
## Contents
179
1. [Installation](#installation)
1810
2. [Usage](#usage)
19-
3. [Configure](#configure)
20-
4. [Supported Frameworks](#supported-frameworks)
11+
3. [Supported Routers](#supported-routers)
12+
4. [Supported Dependencies](#supported-dependencies)
13+
5. [Sample unit test for Mocking/Stubing](#sample-unit-test-for-mockingstubing)
14+
6. [Test with code coverage](#test-with-code-coverage)
15+
7. [Development Setup](#development-setup)
16+
8. [Community support](#community-support)
2117

2218
## Installation
19+
1. First install [Node.js](http://nodejs.org/). Then,
2320
```bash
21+
# for npm package manager
2422
npm i https://github.com/keploy/typescript-sdk
25-
```
26-
27-
## Usage
28-
29-
```js
30-
require("typescript-sdk/dist/integrations/express/register");
31-
```
32-
The require statement should be at the top of your main file (server.js).
33-
34-
Example :
35-
```js
36-
require("typescript-sdk/dist/integrations/express/register");
37-
var express = require('express');
38-
var app = express();
39-
app.get('/', function (req, res) {
40-
res.send('Hello World!\n');
41-
});
42-
43-
var server = app.listen(3000,() =>
44-
console.log(`Example app listening on port 3000!`));
45-
module.exports = server;
46-
```
47-
48-
## Configure
49-
```
50-
export KEPLOY_MODE="test"
51-
export KEPLOY_APP_NAME="my-app"
52-
export KEPLOY_APP_HOST="localhost"
53-
export KEPLOY_APP_PORT=5050 # port on which server is running
54-
export KEPLOY_APP_DELAY=5 # time delay before starting testruns(in seconds)
55-
export KEPLOY_APP_TIMEOUT=100 # should be number
56-
# export KEPLOY_APP_FILTER={"urlRegex":"*"} # should be json not to capture for certain url's
57-
58-
export KEPLOY_SERVER_URL="localhost:6789" # url to self hosted keploy grpc server
59-
# export KEPLOY_SERVER_LICENSE="XXX-XXX-XXX" # hosted keploy server api key
60-
```
61-
### KEPLOY_MODE
62-
There are 3 modes:
63-
- **Record**: Sets to record mode.
64-
- **Test**: Sets to test mode.
65-
- **Off**: Turns off all the functionality provided by the API
66-
67-
**Note:** `KEPLOY_MODE` value is case sensitive.
68-
69-
## Generate E2E tests (with mocks)
7023

71-
```
72-
export KEPLOY_TEST_CASE_PATH="./example" # If KEPLOY_TEST_CASE_PATH is not provided then a folder named keploy-tests will be made containing mocks folder. If KEPLOY_MOCK_PATH is provided then the mocks will be generated there.
73-
export KEPLOY_MOCK_PATH="./exampleMockPath"
24+
# for yarn package manager
25+
yarn add https://github.com/keploy/typescript-sdk
7426
```
7527

76-
**Note:** To enable `Test Export`, add `export ENABLE_TEST_EXPORT=true` in your .env file of [keploy-server](https://github.com/keploy/keploy) repository. If enabled, yaml files containing test cases will be generated in the directory provided by the user. Similarly, mocks will be generated in the yaml files.
28+
2. Install and Start the keploy binary on an independent terminal. Follow [this](https://github.com/keploy/keploy#quick-installation) guide
29+
## Usage
30+
### Generate E2E tests
31+
Keploy can generate end-to-end tests without writing any unit tests file and mocks.
32+
Mocks/stubs are also generated and linked to their respective tests.
33+
These tests can be run just by starting your API server on `test` mode.
34+
We can also add code coverage using the recorded tests. Steps for integration:
35+
1. **Integration**
36+
1. `Add keploy middleware` to your API server. Follow the [Supported Routers](#supported-routers) guide for your router framework.
37+
2. `Wrap the dependencies` of your API server like mongoose, etc. Follow the [Supported Dependencies](#supported-dependencies) guide for your dependencies.
38+
3. `Configuration`: SDK uses environment variables for configuration. "KEPLOY_APP_PORT" is mandatory during, "record"/"test" modes. Other environment variables are optional, since they have default values.
39+
40+
Following is an example of `.env` file configuration.
41+
``` bash
42+
export KEPLOY_APP_PORT=XXXX # port on which API is running. Required and it should be a number
43+
export KEPLOY_MODE="off" # Values: "record" / "test" / "off"(default)
44+
export KEPLOY_APP_NAME="my-app" # [app_ids] for different API applications. Default: "sample-app"
45+
export KEPLOY_APP_HOST="localhost" # Host of API application. Default: "localhost"
46+
export KEPLOY_APP_DELAY=5 # approx time taken by API server to start. Default: 5sec
47+
export KEPLOY_APP_TIMEOUT=100 # request timeout for keploy server. Default: 60sec
48+
# export KEPLOY_APP_FILTER={"urlRegex":"*"} # filters for capturing tcs. It should be a valid JSON
49+
50+
export KEPLOY_SERVER_URL="localhost:6789" # url to running keploy server. Default: "localhost:6789"
51+
# export KEPLOY_SERVER_LICENSE="XXX-XXX-XXX" # hosted keploy server api key
52+
```
53+
2. **Record**
54+
1. Set the `KEPLOY_MODE` to "record" in your .env configuration file.
55+
```bash
56+
export KEPLOY_MODE="record"
57+
```
58+
2. Start your API server on `record` mode.
59+
```bash
60+
# <server>.js should be the main file to start API server.
61+
source .env && node <server>.js
62+
```
63+
3. `Make an API call` on any endpoint of your running API server.
64+
65+
Now, testcases will be generated for the API call along with the integrated dependencies mocks/stubs. These tests and mocks are generated as `readable/editable` yaml files in the */keploy* directory.
66+
3. **Test**
67+
1. Set the `KEPLOY_MODE` to "test" in your .env configuration file.
68+
```bash
69+
export KEPLOY_MODE="test"
70+
```
71+
2. Start your API server on `test` mode.
72+
```bash
73+
# <server>.js should be the main file to start API server.
74+
source .env && node <server>.js
75+
```
76+
77+
🎉TADA: You have made an end-to-end test and tested it without writing any code for test file or managing mocks/stubs.
78+
79+
Keploy can be integrated with testing frameworks like Mocha.js for `code coverage`.
80+
Integartion with fameworks is provided in [Test with code coverage](#test-with-code-coverage) section.
81+
### Mocking/Stubbing for unit tests
82+
These mocks/stubs are realistic and frees you up from writing them manually. Keploy creates `readable/editable` mocks/stubs yaml files which can be referenced in any of your unit-tests tests. Steps to mock/stub external calls:
83+
84+
1. **Wrap the dependencies**:
85+
1. `Initialise keploy context` by calling mock.NewContext in test setup for each testcase.
86+
```js
87+
const { NewContext } = require('typescript-sdk/dist/mock/mock');
88+
// Set your keploy mode and test name of unit test here.
89+
NewContext({Mode: "<record_OR_test_OR_off>", Name: "unique_testcase_name"})
90+
```
91+
2. `Wrap the dependencies` of your unit tests like mongoose, etc. Follow the [Supported Dependencies](#supported-dependencies) guide for your dependencies.
92+
2. **Record**:
93+
1. Set the mode to `record` in NewContext.
94+
```js
95+
// input a unique test name for each testcase in the Name field
96+
NewContext({Mode: "record", Name: "unit_test-1"})
97+
```
98+
2. Run your unit test.
99+
100+
Now, a */mocks* directory is created containing yaml file for each testcase of your unit test.
101+
The yaml files contains the recorded `outputs` of external depedencies as yaml docs.
102+
3. **Test**:
103+
1. Set the mode to `test` in your test setup.
104+
```js
105+
// input a unique test name for each testcase in the Name field
106+
NewContext({Mode: "test", Name: "unit_test-1"})
107+
```
108+
2. Turn off the dependency service like mongoDB server, etc.
109+
3. Run the unit test.
110+
111+
🎉TADA: The unit test will run perfectly, without making any external dependency call.
112+
It uses the recorded outputs from yaml files in generated mocks directory.
113+
114+
An example is provided in [Sample unit test for Mocking/Stubing](#sample-unit-test-for-mockingstubing) section.
77115
78116
## Supported Routers
79117
### 1. Express
118+
Keploy adds a middleware for capturing requests/responses using require hooks. To integrate, just add the following statement before your require statement of `express`.
80119
```js
120+
// Uncomment following blocks to use require in ES Module
121+
/*
122+
import { createRequire } from "module";
123+
const require = createRequire(import.meta.url);
124+
*/
81125
require("typescript-sdk/dist/integrations/express/register");
126+
/*
127+
const express = require('express');
128+
*/
82129
```
83-
The require statement should be at the top of your main file (server.js).
84130
85-
#### Example
131+
Example of CommonJS module express app:
86132
```js
87133
require("typescript-sdk/dist/integrations/express/register");
88134
const express = require('express');
@@ -99,37 +145,49 @@ app.listen(port, () => {
99145
console.log(`Server is running on port: ${port}`);
100146
})
101147
```
102-
Note:- Import statements can't be used. Use require instead of import.
103148
104149
## Supported Dependencies
105-
106150
### 1. Octokit
107-
151+
To integrate, just add this line before require statement of Octokit in your application.
108152
```js
153+
// Uncomment following blocks to use require in ES Module
154+
/*
155+
import { createRequire } from "module";
156+
const require = createRequire(import.meta.url);
157+
*/
109158
require("typescript-sdk/dist/integrations/octokit/require")
159+
/*
160+
const { Octokit, App } = require("octokit");
161+
*/
110162
```
111-
This statement should be at the top of your main file (server.js).
112-
113-
Note:- Import statements can't be used. Only CommonJs support is currently provided.
114-
## Development Setup
115-
116-
- This project uses [Yarn](https://yarnpkg.com/) for package management. To install yarn, please make sure [Node](https://nodejs.org/en/) is installed and then:
117-
118-
```sh
119-
npm i -g yarn
120-
```
121-
122-
- To install local dependencies, assuming you are at root of the project:
123163
124-
```sh
125-
yarn install
164+
### 2. Mongoose
165+
To integrate, just add this line before require statement of mongoose in your application.
166+
```js
167+
// Uncomment following blocks to use require in ES Module
168+
/*
169+
import { createRequire } from "module";
170+
const require = createRequire(import.meta.url);
171+
*/
172+
require("typescript-sdk/dist/integrations/mongoose/require")
173+
/*
174+
const mongoose = require('mongoose');
175+
*/
126176
```
177+
Mongoose package version should be `^6.4.0`. Keploy mocks/stubs outputs for following mongoose methods:
178+
1. find()
179+
2. findOne()
180+
3. save()
181+
4. create()
182+
5. insertMany()
183+
6. updateOne()
184+
7. updateMany()
185+
8. deleteOne()
186+
9. deleteMany()
127187
128-
### How to use mock library
188+
## Sample unit test for Mocking/Stubing
129189
130-
The external calls from unit tests will be recorded and replayed as mocks from yaml files under a directory named mocks.
131-
132-
Following is an example of unit test with octokit :
190+
Following is an example of `CommonJS` module unit test with octokit dependency :
133191
134192
#### Example
135193
```js
@@ -168,7 +226,6 @@ describe('routes', function () {
168226
});
169227
});
170228
```
171-
Above example test is written in commonjs module.
172229
173230
**Note**: Since, this package uses require-in-the-middle for adding hook. Therefore, it is supported for commonjs module currently. Also, you can use require statements in esmodule by:
174231
```js
@@ -177,8 +234,11 @@ import { createRequire } from "module";
177234
const require = createRequire(import.meta.url);
178235
```
179236
180-
### Integration with Mocha testing framework
181-
You just need to do some imports and call a built-in assert function in your code in your unit test file and that's it!!🔥🔥🔥
237+
## Test with code coverage
238+
### Integration with Mocha testing framework
239+
To see code coverage please use nyc mocha and see how many lines are covered!!
240+
241+
You just need to create a unit test file with the following code. And that's it!!🔥🔥🔥
182242
```js
183243
const {runServer} = require('../server') //your server wrapper
184244
const {keploy} = require('typescript-sdk/dist/integrations/express/register')
@@ -197,17 +257,33 @@ describe("test function", ()=>{
197257
})
198258
})
199259
```
200-
Note:- To see code coverage please use nyc mocha and see how many lines are covered!!
201260
202-
Note:- Jest is not supported currently!!
261+
Note:- Since, Jest framework have an isolated environment. Keploy is unable to add hooks for integration.
203262
263+
## Development Setup
204264
205-
- Furthermore, to commit your changes use `yarn commit` instead of `git commit` for better commit experience.
265+
- This project uses [Yarn](https://yarnpkg.com/) for package management. To install yarn, please make sure [Node](https://nodejs.org/en/) is installed and then:
266+
267+
```sh
268+
npm i -g yarn
269+
```
270+
271+
- To install local dependencies, assuming you are at root of the project:
206272
273+
```sh
274+
yarn install
275+
```
276+
277+
- To generate the js grpc files from services.proto:
278+
```sh
279+
yarn proto-loader-gen-types --grpcLib=@grpc/grpc-js --outDir=proto/ proto/*.proto
280+
```
207281
- For VSCode setup, make sure these extensions are installed:
208282
- [EditorConfig](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig)
209283
- [Eslint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
210284
285+
- Furthermore, to commit your changes use `yarn commit` instead of `git commit` for better commit experience.
286+
211287
## Community support
212288
We'd love to collaborate with you to make Keploy great. To get started:
213289
* [Slack](https://join.slack.com/t/keploy/shared_invite/zt-12rfbvc01-o54cOG0X1G6eVJTuI_orSA) - Discussions with the community and the team.

0 commit comments

Comments
 (0)