【问题标题】:Unable to cover the code using Jasmine Spy无法使用 Jasmine Spy 覆盖代码
【发布时间】:2021-04-19 16:26:51
【问题描述】:

我正在使用打字稿编写代码覆盖率测试用例。我正在使用 Jasmine spyOn,但它没有被覆盖。但是有些方法被覆盖了,我没有收到任何错误。我需要你的指导来解决这个问题。我在下面提供了实际代码。

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;
    }
}

我在规范代码下面写。

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);
});

我还在下面提供了未涵盖的屏幕截图。

【问题讨论】:

  • 请帮帮我。

标签: javascript node.js typescript jasmine spyon


【解决方案1】:

你也许应该看看这里 => Code Coverage issue when spyon is used

也就是说,我将在这里复制内容,并预计会更容易一些。

“因为 spy 实际上替换了函数调用。你必须进行两个测试:第一个将测试函数是否被实际调用(你做了什么),第二个将测试你的 onNext 函数”作者 – user4676340。

所以,请执行ApiUtil.YouFunction() 让它确实被调用。

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 2016-02-29
    • 2013-04-16
    • 1970-01-01
    • 2021-09-10
    • 2018-09-13
    • 2022-06-17
    • 1970-01-01
    相关资源
    最近更新 更多