Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding v2 for TS sdk #92

Merged
merged 1 commit into from
Oct 30, 2023

Conversation

shivamsouravjha
Copy link
Contributor

@shivamsouravjha shivamsouravjha commented Sep 6, 2023

Solves: issue

package.jsonfile

"scripts": {
    "test": "jest --coverage",
    "start": "node src/app.js",
    "dev": "nodemon src/app.js",
    "coverage": "nyc npm test && npm run coverage:merge && npm run coverage:report",
    "coverage:merge": "nyc merge ./coverage .nyc_output/out.json",
    "coverage:report": "nyc report --reporter=lcov --reporter=text"
  },

jest.config.js file

// jest.config.ts
import type { InitialOptionsTsJest } from 'ts-jest/dist/types';

const config: InitialOptionsTsJest = {
  preset: 'ts-jest', // We will keep this if you still have TypeScript files like your Jest config
  testEnvironment: 'node', // Specifies that tests should be run in a Node environment

  // The glob patterns Jest uses to detect test files
  testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)+(spec|test).js?(x)'],

  // Indicates whether each individual test should be reported during the run
  verbose: true,

  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  collectCoverageFrom: [
    'src/**/*.{js,jsx}', // Only include .js and .jsx files from the src directory
    '!src/**/*.d.ts', // Exclude TypeScript declaration files if any
    '!src/**/*.{test,spec}.js', // Exclude test files themselves from coverage
    '!src/**/__tests__/**', // Exclude test directories from coverage
  ],

  // The directory where Jest should output its coverage files
  coverageDirectory: 'coverage',

  // A list of reporter names that Jest uses when writing coverage reports
  coverageReporters: ['json', 'lcov', 'text', 'clover'],

  // An array of file extensions your modules use
  moduleFileExtensions: ['js', 'jsx', 'json', 'node'],
};

export default config;

test.test.js file

const {
    RunKeployServer,
    FetchTestSets,
    RunTestSet,
    FetchTestSetStatus,
    StopKeployServer,
    TestRunStatus,
    setTestRunCompletionStatus,
    cleanupProcesses,
} = require('../typescript-sdk/keployV2/keployCli');
import mongoose from 'mongoose';

const app = require('./app'); // Adjust the path to point to your app.js file
let server;
const { expect } = require('@jest/globals');

describe('Keploy Server Tests', () => {
    let pid;
    beforeAll(async () => {
        setTestRunCompletionStatus(false)
        console.debug("Running keploy tests along with unit tests");
        pid = process.pid;
        console.log("Sending app pid to keploy: " + pid);

        try {
            console.log("Starting keploy server");
            RunKeployServer(pid, 10, <pathToKeployBinary>, 0);
            // wait for the keploy to load hooks
            await new Promise(resolve => setTimeout(resolve, 20000));
        } catch (error) {
            console.error("Error starting Keploy server:", error);
            throw error; // propagate the error so that Jest can recognize it
        }
    }, 6500000);

    afterAll(async () => {
        setTestRunCompletionStatus(true)
        await mongoose.disconnect();
        console.log("Stopping keploy server");
        try {
            await StopKeployServer();
            console.log("Keploy server stopped.");
        } catch (error) {
            console.error("Error stopping Keploy server:", error);
            throw error; // propagate the error so that Jest can recognize it
        }
        cleanupProcesses();
    }, 7000000);

    test('TestKeploy', async () => {
        let testResult = true;
        const MAX_TIMEOUT = 100000; // 1 minute timeout, adjust as necessary
        let startTime = Date.now();

        try {
            const testSets = await FetchTestSets();

            if (testSets === null) {
                throw new Error('Test sets are null');
            }

            console.log("TestSets: ", [...testSets]);

            console.log("starting user application");

            let result = true;
            for (let testset of testSets) {
                try {
                    console.log("now starting");
                    server = app.listen(process.env.PORT || 5002, () => {
                        console.log('User application started on port', process.env.PORT || 5002);
                    });
                } catch (error) {
                    console.log("got error while starting user application");
                    throw new Error(`User Application Error: ${error.message}`);
                }
                const testRunId = await RunTestSet(testset);
                let testRunStatus;

                while (true) {
                    // check status every 2 sec
                await new Promise(res => setTimeout(res, 2000));
                    testRunStatus = await FetchTestSetStatus(testRunId);
                    if (testRunStatus === TestRunStatus.RUNNING) {
                        console.log("testRun still in progress");

                        // Check if timeout has been reached
                        if (Date.now() - startTime > MAX_TIMEOUT) {
                            console.log("Timeout reached, exiting loop");
                            break;
                        }

                        continue;
                    }
                    break;
                }

                if (testRunStatus === TestRunStatus.FAILED) {
                    console.log("testrun failed");
                    result = false;
                } else if (testRunStatus === TestRunStatus.PASSED) {
                    console.log("testrun passed");
                    result = true;
                }
                console.log(`TestResult of [${testset}]: ${result}`);
                testResult = testResult && result;
                server && server.close();
            } // Updated this line to assert on testResult instead of hardcoded true
        } catch (error) {
            throw error; // propagate the error so that Jest can recognize it
        }
        expect(testResult).toBeTruthy(); // Updated this line to assert on testResult instead of hardcoded true

    }, 30000000);
}, 30000000000);

tsconfig.json

```{ "compilerOptions": { "target": "es6", "module": "commonjs", "types": ["jest", "node"] } } ```

const command = [
'sudo',
'-S',
'/home/shivamsouravjha.linux/keploy/server',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the binary of keploy should be installed globally using Readme.

@nehagup nehagup merged commit 8304c21 into keploy:main Oct 30, 2023
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants