简体   繁体   English

无法使用 Jasmine Spy 覆盖代码

[英]Unable to cover the code using Jasmine Spy

I am writing test cases for code coverage using typescript. I am using Jasmine spyOn , but it is not covered.我正在使用 typescript 编写代码覆盖测试用例。我正在使用 Jasmine spyOn ,但未涵盖。 But some of the methods are covered and I am not getting any error.但是有些方法已经涵盖了,我没有收到任何错误。 I need your guidance to resolve this.我需要你的指导来解决这个问题。 I provide below the actual code.我在下面提供实际代码。

import {IncomingMessage} from "http";
import * as https from "https";
import * as logger from "winston";

export class ApiUtil {
    public static async authenticate(params: object): Promise<string> {
        let response: Promise<string> = null;
        response = new Promise((resolve) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getAuthResponse(res).then((resstr) => {
                        resolve(resstr);
                    })
                        .catch((error) => {
                            logger.info("Internal unexpected authentication error: ", error);
                            if (error === "NOT_FOUND") {
                                resolve("NOT_FOUND");
                            } else {
                                resolve("Error");
                            }
                        });
                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    resolve("Error");
                });
                req.end();
            } catch (error) {
                logger.info("Unexpected Authentication Error: ", error);
                logger.info("To DO");
            }
        });
        return response;
    }

    public static getAuthParams(host: string, userName: string, pwc: string): object {
        const base64Credential = ApiUtil.getBase64EncodeCredential(userName, pwc);
        logger.info("Base64 Credential successfully received");
        const params: object = {
            agent: false,
            headers: {
                Authorization: base64Credential,
                accepts: "application/json",
            },
            hostname: host,
            method: "POST",
            path: "/LOGIN_REST_URI",
            rejectUnauthorized: false,
        };
        return params;
    }

    public static async getAuthResponse(res: IncomingMessage): Promise<string> {
        return new Promise((resolve, reject) => {
            ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                resolve(resstr.value);
            })
                .catch((e) => {
                    logger.info("Unexpected error while getting authentication response: ", e);
                    reject(e);
                });

        });
    }

    public static async getRestAPIResponseText(res: IncomingMessage): Promise<any> {
        return new Promise((resolve, reject) => {
            if (res && res.statusCode === 200) {
                res.on("data", (dataChunk: string) => {
                    logger.info("Actual API call response");
                    const body = JSON.parse(dataChunk);
                    logger.info("Actual Body received");
                    resolve(body);
                });
            } else if (res && res.statusCode === 404) {
                reject(res.statusMessage);
            } else {
                reject(null);
            }
        });

    }

    public static getBase64EncodeCredential(userName: string, pwc: string): string {
        let b64Encvalue: string = null;
        b64Encvalue = "Basic " + new Buffer(userName + ":" + pwc).toString("base64");
        return b64Encvalue;
    }

    public static getApiParams(vmwareSessionId: string, host: string, restApiURI: string): object {
        logger.info("vCenter Session Id received");
        const options: object = {
            headers: {
                "vmware-api-session-id": vmwareSessionId,
            },
            hostname: host,
            method: "GET",
            path: restApiURI,
            rejectUnauthorized: false,
            requestCert: true,
        };
        return options;
    }

    public static async getApiResponse(vmwareSessionId: string, host: string, restAPIURI: string): Promise<any> {
        let doesExist: Promise<any> = null;
        const params: object = ApiUtil.getApiParams(vmwareSessionId, host, restAPIURI);
        doesExist = new Promise((resolve, reject) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                        resolve(resstr);
                    })
                        .catch((e) => {
                            logger.info("Inner Unexpected error while calling  getApiResponse(): ", e);
                            reject(null);
                        });

                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    resolve(null);
                });
                req.end();
            } catch (error) {
                logger.info("Outer Unexpected error while calling  getApiResponse(): ", error);
                reject(error);
            }
        });
        return doesExist;
    }

    public static async getVersionApiResponse(vmwareSessionId: string, host: string, restAPIURI: string):
        Promise<string> {
        let versionDetails: Promise<string> = null;
        const params: object = ApiUtil.getApiParams(vmwareSessionId, host, restAPIURI);
        versionDetails = new Promise((resolve, reject) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                        resolve(resstr.value.version);
                    })
                        .catch((e) => {
                            logger.info("Internal Unexpected Error while calling getVersionApiResponse(): ", e);
                            resolve(null);
                        });

                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    resolve(null);
                });
                req.end();
            } catch (error) {
                logger.info("Unexpected Error while calling getVersionApiResponse(): ", error);
                reject(error);
            }
        });
        return versionDetails;
    }

    public static async getVersionNBuildApiResponse(vmwareSessionId: string, host: string, restAPIURI: string):
        Promise<any> {
        const versionNBuild: any = {version: null, build: null};
        let versionInfo: Promise<any> = null;
        const params: object = ApiUtil.getApiParams(vmwareSessionId, host, restAPIURI);
        versionInfo = new Promise((resolve, reject) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                        versionNBuild.version = resstr.value.version;
                        versionNBuild.build = resstr.value.build;
                        resolve(versionNBuild);
                    })
                        .catch((e) => {
                            logger.info("Internal Unexpected Error while calling getVersionApiResponse(): ", e);
                            versionNBuild.version = null;
                            versionNBuild.build = null;
                            resolve(versionNBuild);
                        });

                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    versionNBuild.version = null;
                    versionNBuild.build = null;
                    resolve(versionNBuild);
                });
                req.end();
            } catch (error) {
                logger.info("Unexpected Error while calling getVersionApiResponse(): ", error);
                reject(error);
            }
        });
        return versionInfo;
    }
}

I am writing below the spec code.我在规范代码下面写。

import { ApiUtil } from "./api.util";

describe("API Utility", () => {

    it("should not validate authentication", ((done) => {
        // spyOn(https, "request").and.returnValue(Promise.resolve("someValue"));
        spyOn(ApiUtil, "getBase64EncodeCredential").and.returnValue("someValue1");
        spyOn(ApiUtil, "getAuthParams").and.returnValue(Promise.resolve("someValue"));
        spyOn(ApiUtil, "getRestAPIResponseText").and.returnValue("clusterName");
        spyOn(ApiUtil, "getAuthResponse").and.returnValue(Promise.resolve("someResponse"));
        spyOn(ApiUtil, "getApiResponse").and.returnValue("[]");
        const params: object = {};

        ApiUtil.authenticate(params).then( (response) => {
            expect(response).toBe("Error");
            done();
        });

    }), 30000);
});

I also provide below the screenshot which is not covered.我还在下面提供了未涵盖的屏幕截图。

在此处输入图像描述

You maybe should have a look here => Code Coverage issue when spyon is used您也许应该在这里看看 => 使用 spyon 时的代码覆盖率问题

That said, I'm going to replicate the content here and anticipate a little bit to make it easier.也就是说,我将在此处复制内容并进行一些预期以使其更容易。

"Because the spy actually replaces the function call. You have to make two tests: the first will test if the function is actually called (what you did), and the second will test your onNext function" By – user4676340. “因为间谍实际上替换了 function 调用。您必须进行两项测试:第一项将测试 function 是否实际被调用(您所做的),第二项将测试您的 onNext 函数”作者 – user4676340。

So, do ApiUtil.YouFunction() to let it have been called indeed.所以,做ApiUtil.YouFunction()让它确实被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM