Skip to content

Commit

Permalink
test: add SvgRenderer test
Browse files Browse the repository at this point in the history
  • Loading branch information
yapyuyou committed Mar 18, 2024
1 parent cc2841c commit 7bebdaa
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"lint:fix": "npm run lint -- --fix",
"storybook": "storybook dev -p 6006",
"storybook:build": "storybook build -o docs",
"test": "jest --ci",
"test": "jest --ci SvgRenderer",
"test:coverage": "npm run test -- --coverage",
"test:watch": "npm run test -- --watch",
"semantic-release": "semantic-release"
Expand Down
72 changes: 72 additions & 0 deletions src/components/renderer/SvgRenderer.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Valid / Invalid urls
// v4 with Svg url with response and multibase
// v4 with Svg data and multibase
// v4 with Svg url with tampered response and no multibase
// v4 with Svg url with bad response and multibase
// v4 with Svg url with tampered response and multibase
// v4 with tampered Svg data
// v2 with Svg url with response and multibase

// import React from "react";
import { v4 } from "@govtechsg/open-attestation";
import { render } from "@testing-library/react";
import { SvgRenderer } from "./SvgRenderer";
import fs from "fs";
// import { UnsupportedRenderer } from "./UnsupportedRenderer";

const v4WithSvgUrlAndDigestMultibase = {
// TODO: Update type to v4.OpenAttestationDocument
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://schemata.openattestation.com/com/openattestation/4.0/alpha-context.json",
],
issuer: {
id: "did:ethr:0xB26B4941941C51a4885E5B7D3A1B861E54405f90",
type: "OpenAttestationIssuer",
name: "Government Technology Agency of Singapore (GovTech)",
identityProof: { identityProofType: v4.IdentityProofType.DNSDid, identifier: "example.openattestation.com" },
},
credentialStatus: { type: "OpenAttestationCredentialStatus", credentialStatusType: v4.CredentialStatusType.None },
renderMethod: {
id: "http://mockbucket.com/static/svg_test.svg",
type: "SvgRenderingTemplate2023",
name: "SVG Certificate",
digestMultibase: "z2Z98fDGXMKgjxZpWNFBE2c8fRPH5dQ9Zc2Y15vDHLHdm",
url: "https://ignorethisurlthisisjusttopasstheschemacheck.com",
renderMethodType: v4.RenderMethodType.EmbeddedRenderer,
},
credentialSubject: {
id: "urn:uuid:a013fb9d-bb03-4056-b696-05575eceaf42",
type: ["SvgExample"],
course: { name: "SVG Basics Workshop", fromDate: "01/01/2024", endDate: "16/01/2024" },
recipient: { name: "TAN CHEN CHEN" },
},
};

describe("component SvgRenderer with 200 response", () => {
// const mockBlob = jest.fn().mockResolvedValueOnce({
// arrayBuffer: jest.fn().mockResolvedValueOnce("your array buffer data"),
// });

const mockSvg = fs.readFileSync("./src/components/renderer/fixtures/example_cert.svg");
const mockBlob = jest.fn().mockResolvedValue(new Blob([mockSvg], { type: "image/svg+xml" }));
const mockResponse = { blob: mockBlob };
global.fetch = jest.fn().mockResolvedValueOnce(mockResponse);

Check failure on line 54 in src/components/renderer/SvgRenderer.test.tsx

View workflow job for this annotation

GitHub Actions / Test

Use jest.spyOn() instead

it("should render correctly", () => {

Check failure on line 56 in src/components/renderer/SvgRenderer.test.tsx

View workflow job for this annotation

GitHub Actions / Test

Test has no assertions
const svgRef = {
current: null,
};

const svgUrl = v4WithSvgUrlAndDigestMultibase.renderMethod.id;

const { getByText } = render(

Check warning on line 63 in src/components/renderer/SvgRenderer.test.tsx

View workflow job for this annotation

GitHub Actions / Test

'getByText' is assigned a value but never used
<SvgRenderer svgOrUrl={svgUrl} document={v4WithSvgUrlAndDigestMultibase} svgRef={svgRef} />

Check failure on line 64 in src/components/renderer/SvgRenderer.test.tsx

View workflow job for this annotation

GitHub Actions / Test

'React' must be in scope when using JSX
);
// const { getByText } = render(
// <UnsupportedRenderer attachment={{ type: "application/epub+zip", data: "", filename: "" }} />
// );
// expect(getByText("Rendering of this type of attachment is not supported.")).toBeDefined();
// expect(getByText("Please check your mime-type: application/epub+zip")).toBeDefined();
});
});
21 changes: 15 additions & 6 deletions src/components/renderer/SvgRenderer.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { OpenAttestationDocument, v4 } from "@govtechsg/open-attestation";
import { base58btc } from "multiformats/bases/base58";
import { Digest } from "multiformats/dist/src/hashes/digest";
import { sha256 } from "multiformats/hashes/sha2";
import { bases, hashes, digest } from "multiformats/basics";
// import { basics } from "multiformats"
// import { Digest } from "multiformats/hashes/digest";
// import { sha256 } from "multiformats/hashes/sha2";
// import { base58btc } from "multiformats/bases/base58";
import React, { CSSProperties, FunctionComponent, useEffect, useState } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { ConnectionFailureTemplate } from "../../DefaultTemplate";
Expand All @@ -16,6 +18,7 @@ interface SvgRendererProps {
className?: string;
sandbox?: string;
onConnected?: () => void; // Optional call method to call once svg is loaded
useWithoutV4?: boolean;
}
export const SvgRenderer: FunctionComponent<SvgRendererProps> = ({
svgOrUrl,
Expand All @@ -25,12 +28,18 @@ export const SvgRenderer: FunctionComponent<SvgRendererProps> = ({
className,
sandbox = "allow-same-origin",
onConnected,
useWithoutV4 = false,
}) => {
const [buffer, setBuffer] = useState<ArrayBuffer>();
const [svgData, setSvgData] = useState<string>("");
const [isError, setIsError] = useState<boolean>(false);
const [source, setSource] = useState<string>("");
const docAsAny = document as any; // TODO: update type to v4.OpenAttestationDocument
let docAsAny: any;
if (useWithoutV4) {
docAsAny = document as any;
} else {
docAsAny = document as any; // TODO: update type to v4.OpenAttestationDocument
}

// 1. Fetch svg data from url if needed, if not directly proceed to checksum
useEffect(() => {
Expand Down Expand Up @@ -67,9 +76,9 @@ export const SvgRenderer: FunctionComponent<SvgRendererProps> = ({
const text = new TextDecoder().decode(svgUint8Array);

if (digestMultibaseInDoc) {
const shaDigest = sha256.digest(svgUint8Array) as Promise<Digest<18, number>>;
const shaDigest = hashes.sha256.digest(svgUint8Array) as Promise<digest.Digest<18, number>>;
shaDigest.then((res: any) => {
const recomputedDigestMultibase = base58btc.encode(res.digest);
const recomputedDigestMultibase = bases.base58btc.encode(res.digest);
console.log(`Original checksum is`, digestMultibaseInDoc);
console.log(`Recomputed checksum is`, recomputedDigestMultibase);
if (recomputedDigestMultibase === digestMultibaseInDoc) {
Expand Down
12 changes: 12 additions & 0 deletions src/components/renderer/fixtures/example_cert.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 7bebdaa

Please sign in to comment.