#javascript #node.js #typescript #jasmine #spyon
Вопрос:
Я пишу тестовые примеры для покрытия кода с помощью typescript. Я использую Жасмин 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 amp;amp; 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 amp;amp; 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);
});
Я также привожу ниже скриншот, который не освещен.
Комментарии:
1. Пожалуйста, помогите мне.