Skip to content

Commit 1d37bbf

Browse files
committed
feat(github actions and wrappednodefetched.test.js): integrated github action and wrote unit test
For code coverage added unit test for wrappedNodeFetch function and integrated git hub actions. test #354 Signed-off-by: Hermione Dadheech <hermionedadheech@gmail.com>
1 parent 88691f5 commit 1d37bbf

File tree

5 files changed

+323
-2
lines changed

5 files changed

+323
-2
lines changed

.github/workflows/ci.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,6 @@ jobs:
3333

3434
- name: Check commits messages
3535
uses: wagoid/commitlint-github-action@v3
36+
37+
- name: Run the tests
38+
run: npm test -- --coverage

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,8 @@ node_modules
184184

185185
# Build files
186186

187-
dist
187+
dist
188+
189+
#Test coverage report
190+
191+
coverage

jest.config.ts

Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
/*
2+
* For a detailed explanation regarding each configuration property and type check, visit:
3+
* https://jestjs.io/docs/configuration
4+
*/
5+
6+
export default {
7+
preset:'ts-jest',
8+
testEnvironment:'node',
9+
// All imported modules in your tests should be mocked automatically
10+
// automock: false,
11+
12+
// Stop running tests after `n` failures
13+
// bail: 0,
14+
15+
// The directory where Jest should store its cached dependency information
16+
// cacheDirectory: "/tmp/jest_rs",
17+
18+
// Automatically clear mock calls, instances, contexts and results before every test
19+
clearMocks: true,
20+
21+
// Indicates whether the coverage information should be collected while executing the test
22+
collectCoverage: true,
23+
24+
// An array of glob patterns indicating a set of files for which coverage information should be collected
25+
// collectCoverageFrom: undefined,
26+
27+
// The directory where Jest should output its coverage files
28+
coverageDirectory: "coverage",
29+
30+
// An array of regexp pattern strings used to skip coverage collection
31+
// coveragePathIgnorePatterns: [
32+
// "/node_modules/"
33+
// ],
34+
35+
// Indicates which provider should be used to instrument code for coverage
36+
coverageProvider: "v8",
37+
38+
// A list of reporter names that Jest uses when writing coverage reports
39+
// coverageReporters: [
40+
// "json",
41+
// "text",
42+
// "lcov",
43+
// "clover"
44+
// ],
45+
46+
// An object that configures minimum threshold enforcement for coverage results
47+
// coverageThreshold: undefined,
48+
49+
// A path to a custom dependency extractor
50+
// dependencyExtractor: undefined,
51+
52+
// Make calling deprecated APIs throw helpful error messages
53+
// errorOnDeprecated: false,
54+
55+
// The default configuration for fake timers
56+
// fakeTimers: {
57+
// "enableGlobally": false
58+
// },
59+
60+
// Force coverage collection from ignored files using an array of glob patterns
61+
// forceCoverageMatch: [],
62+
63+
// A path to a module which exports an async function that is triggered once before all test suites
64+
// globalSetup: undefined,
65+
66+
// A path to a module which exports an async function that is triggered once after all test suites
67+
// globalTeardown: undefined,
68+
69+
// A set of global variables that need to be available in all test environments
70+
// globals: {},
71+
72+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
73+
// maxWorkers: "50%",
74+
75+
// An array of directory names to be searched recursively up from the requiring module's location
76+
// moduleDirectories: [
77+
// "node_modules"
78+
// ],
79+
80+
// An array of file extensions your modules use
81+
// moduleFileExtensions: [
82+
// "js",
83+
// "mjs",
84+
// "cjs",
85+
// "jsx",
86+
// "ts",
87+
// "tsx",
88+
// "json",
89+
// "node"
90+
// ],
91+
92+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
93+
// moduleNameMapper: {},
94+
95+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
96+
// modulePathIgnorePatterns: [],
97+
98+
// Activates notifications for test results
99+
// notify: false,
100+
101+
// An enum that specifies notification mode. Requires { notify: true }
102+
// notifyMode: "failure-change",
103+
104+
// A preset that is used as a base for Jest's configuration
105+
// preset: undefined,
106+
107+
// Run tests from one or more projects
108+
// projects: undefined,
109+
110+
// Use this configuration option to add custom reporters to Jest
111+
// reporters: undefined,
112+
113+
// Automatically reset mock state before every test
114+
// resetMocks: false,
115+
116+
// Reset the module registry before running each individual test
117+
// resetModules: false,
118+
119+
// A path to a custom resolver
120+
// resolver: undefined,
121+
122+
// Automatically restore mock state and implementation before every test
123+
// restoreMocks: false,
124+
125+
// The root directory that Jest should scan for tests and modules within
126+
// rootDir: undefined,
127+
128+
// A list of paths to directories that Jest should use to search for files in
129+
// roots: [
130+
// "<rootDir>"
131+
// ],
132+
133+
// Allows you to use a custom runner instead of Jest's default test runner
134+
// runner: "jest-runner",
135+
136+
// The paths to modules that run some code to configure or set up the testing environment before each test
137+
// setupFiles: [],
138+
139+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
140+
// setupFilesAfterEnv: [],
141+
142+
// The number of seconds after which a test is considered as slow and reported as such in the results.
143+
// slowTestThreshold: 5,
144+
145+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
146+
// snapshotSerializers: [],
147+
148+
// The test environment that will be used for testing
149+
// testEnvironment: "jest-environment-node",
150+
151+
// Options that will be passed to the testEnvironment
152+
// testEnvironmentOptions: {},
153+
154+
// Adds a location field to test results
155+
// testLocationInResults: false,
156+
157+
// The glob patterns Jest uses to detect test files
158+
// testMatch: [
159+
// "**/__tests__/**/*.[jt]s?(x)",
160+
// "**/?(*.)+(spec|test).[tj]s?(x)"
161+
// ],
162+
163+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
164+
// testPathIgnorePatterns: [
165+
// "/node_modules/"
166+
// ],
167+
168+
// The regexp pattern or array of patterns that Jest uses to detect test files
169+
// testRegex: [],
170+
171+
// This option allows the use of a custom results processor
172+
// testResultsProcessor: undefined,
173+
174+
// This option allows use of a custom test runner
175+
// testRunner: "jest-circus/runner",
176+
177+
// A map from regular expressions to paths to transformers
178+
// transform: undefined,
179+
180+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
181+
// transformIgnorePatterns: [
182+
// "/node_modules/",
183+
// "\\.pnp\\.[^\\/]+$"
184+
// ],
185+
186+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
187+
// unmockedModulePathPatterns: undefined,
188+
189+
// Indicates whether each individual test should be reported during the run
190+
// verbose: undefined,
191+
192+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
193+
// watchPathIgnorePatterns: [],
194+
195+
// Whether to use watchman for file crawling
196+
// watchman: true,
197+
};

package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
"scripts": {
99
"build": "tsc && cp ./proto/services.proto ./dist/proto/",
1010
"prepare": "npm run build",
11-
"commit": "cz"
11+
"commit": "cz",
12+
"test": "jest"
1213
},
1314
"repository": "git@github.com:keploy/typescript-sdk.git",
1415
"author": "Rajat Sharma <lunasunkaiser@gmail.com>",
@@ -18,6 +19,7 @@
1819
"@commitlint/config-conventional": "^16.2.1",
1920
"@types/cors": "^2.8.12",
2021
"@types/express": "^4.17.13",
22+
"@types/jest": "^29.4.0",
2123
"@types/merge-descriptors": "^1.0.1",
2224
"@types/node": "^18.7.18",
2325
"@types/node-fetch": "^2.6.2",
@@ -31,7 +33,10 @@
3133
"eslint-plugin-import": "^2.25.4",
3234
"eslint-plugin-prettier": "^4.0.0",
3335
"husky": "^7.0.4",
36+
"jest": "^29.5.0",
3437
"prettier": "^2.5.1",
38+
"ts-jest": "^29.0.5",
39+
"ts-node": "^10.9.1",
3540
"typescript": "^4.6.2"
3641
},
3742
"config": {

test/wrappedNodeFetch.test.ts

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import { wrappedNodeFetch } from '../integrations/octokit/require';
2+
import { Response } from 'node-fetch';
3+
import { createExecutionContext } from '../src/context';
4+
describe('wrappedNodeFetch', () => {
5+
it('should call fetch function with correct arguments in record mode', async () => {
6+
const mockFetch = jest.fn().mockResolvedValueOnce(new Response());
7+
const ctx = {
8+
context:{
9+
mode: 'record',
10+
testId: 'testId',
11+
mocks: [],
12+
deps: [],
13+
}
14+
};
15+
createExecutionContext(ctx)
16+
const wrappedFetch = (wrappedNodeFetch(mockFetch) as any).bind({ fetch: mockFetch });
17+
const url = 'http://example.com';
18+
const options = {
19+
method: 'GET',
20+
};
21+
const response = await wrappedFetch(url, options);
22+
console.log(response,"RESPONSE")
23+
24+
expect(mockFetch).toHaveBeenCalledWith(url, options);
25+
expect(response).toBeInstanceOf(Response);
26+
});
27+
28+
it('should return mocked response in test mode', async () => {
29+
const mockResponse = new Response('mocked response');
30+
const mockFetch = jest.fn().mockResolvedValue(mockResponse);
31+
const ctx = {
32+
context:{
33+
mode: 'test',
34+
testId: 'testId',
35+
mocks: [
36+
{
37+
Version: 'V1_BETA2',
38+
Name: 'testId',
39+
Kind: 'HTTP',
40+
Spec: {
41+
Metadata: {
42+
name: 'node-fetch',
43+
url: 'http://example.com',
44+
options: { method: 'GET' },
45+
type: 'HTTP_CLIENT',
46+
},
47+
Req: {
48+
URL: 'http://example.com',
49+
Body: '',
50+
Header: {},
51+
Method: 'GET',
52+
},
53+
Res: {
54+
StatusCode: 200,
55+
Header: { 'content-type': { Value: ['text/plain'] } },
56+
Body: 'mocked response',
57+
},
58+
},
59+
},
60+
],
61+
deps: [],
62+
}
63+
};
64+
createExecutionContext(ctx)
65+
66+
const wrappedFetch = (wrappedNodeFetch(mockFetch) as any).bind({ fetch: mockFetch });
67+
const url = 'http://example.com';
68+
const options = {
69+
method: 'GET',
70+
};
71+
const response = await wrappedFetch(url, options);
72+
console.log(response,"RESPONSE")
73+
expect(response).toEqual(mockResponse);
74+
});
75+
76+
it('should return undefined if execution context is not present in record mode', async () => {
77+
const mockFetch = jest.fn().mockResolvedValue(new Response());
78+
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
79+
const wrappedFetch = (wrappedNodeFetch(mockFetch) as any).bind({ fetch: mockFetch });
80+
const url = 'http://example.com';
81+
const options = {
82+
method: 'GET',
83+
};
84+
const response = await wrappedFetch(url, options);
85+
expect(consoleSpy).toHaveBeenCalledWith('keploy context is not present to mock dependencies');
86+
expect(response).toBeUndefined();
87+
});
88+
89+
it('should call fetch function with correct arguments in off mode', async () => {
90+
const mockFetch = jest.fn().mockResolvedValueOnce(new Response());
91+
const ctx = {
92+
context:{
93+
context: 'off',
94+
testId: 'testId',
95+
mocks: [],
96+
deps: [],
97+
}
98+
};
99+
createExecutionContext(ctx)
100+
101+
const wrappedFetch = (wrappedNodeFetch(mockFetch) as any).bind({ fetch: mockFetch });
102+
const url = 'http://example.com';
103+
const options = {
104+
method: 'GET',
105+
};
106+
const response = await wrappedFetch(url, options);
107+
console.log(response,"RESPONSE")
108+
109+
expect(mockFetch).toHaveBeenCalledWith(url, options);
110+
expect(response).toBeInstanceOf(Response);
111+
});
112+
});

0 commit comments

Comments
 (0)