Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Unit test
Unit testing Apps SDK packages.
Running this example
To run this example locally:
-
If you haven't already, create a new app in the Developer Portal(opens in a new tab or window). For more information, refer to our Quickstart guide.
-
In your app's configuration on the Developer Portal(opens in a new tab or window), ensure the "Development URL" is set to
http://localhost:8080
. -
Clone the starter kit:
git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.gitcd canva-apps-sdk-starter-kitSHELL -
Install dependencies:
npm installSHELL -
Run the example:
npm run start unit_testSHELL -
Click the Preview URL link shown in the terminal to open the example in the Canva editor.
Example app source code
// For usage information, see the README.md file.import {Button,Column,Columns,Rows,Swatch,Text,Title,} from "@canva/app-ui-kit";import * as styles from "styles/components.css";import { requestOpenExternalUrl } from "@canva/platform";import type { Anchor } from "@canva/asset";import { openColorSelector } from "@canva/asset";import { useState } from "react";import { useFeatureSupport } from "utils/use_feature_support";import { addPage } from "@canva/design";import { CanvaError } from "@canva/error";export const DOCS_URL = "https://www.canva.dev/docs/apps/";export const API_URL = `${DOCS_URL}api/v2/platform-request-open-external-url/`;export const QUOTA_ERROR ="Sorry, you cannot add any more pages. Please remove an existing page and try again.";export const App = () => {const [error, setError] = useState<string | undefined>();const [color, setColor] = useState<string | undefined>(undefined);const handleSwatchClick = async (boundingRect: Anchor) => {const closeFn = await openColorSelector(boundingRect, {onColorSelect: (e) => {if (e.selection.type === "solid") {setColor(e.selection.hexString);}closeFn();},scopes: ["solid"],});};const handleAddPage = async () => {try {await addPage({title: "New Page Added By Button",background: {color: color || "#acbdef",},});} catch (e) {if (e instanceof CanvaError) {switch (e.code) {case "quota_exceeded":setError(QUOTA_ERROR);break;// TODO: handle other errors uniquely if requireddefault:setError(e.message);break;}}}};const isSupported = useFeatureSupport();const canAddPage = isSupported(addPage);return (<div className={styles.scrollContainer}><Rows spacing="1u">{error && <Text tone="critical">{error}</Text>}{/* === This swatch is used in the unit test to demonstrate listening for calls to a Canva Apps API */}<div id="color-selector"><Title>Color Selector</Title><Swatchfill={[color]}onClick={(e) =>handleSwatchClick(e.currentTarget.getBoundingClientRect())}/></div>{/* === These buttons are used in the unit test to demonstrate checking for parameters passed to Canva Apps APIs === */}<Title>Open External Link</Title><Columns spacing="1u"><Column><Buttonstretchvariant="secondary"onClick={() => requestOpenExternalUrl({ url: DOCS_URL })}>Apps SDK</Button></Column><Column><Buttonvariant="secondary"stretchonClick={() => requestOpenExternalUrl({ url: API_URL })}>API Reference</Button></Column></Columns>{/* === Displaying this section is contingent on the feature being supported - this can be mocked in a unit test to check both paths */}<Title>Add Page</Title>{canAddPage ? (<Button variant="secondary" onClick={() => handleAddPage()}>Add Page</Button>) : (<Text>Adding pages is not supported in this design. Please try thisexample in a different design.</Text>)}</Rows></div>);};
TYPESCRIPT
import { AppUiProvider } from "@canva/app-ui-kit";import { createRoot } from "react-dom/client";import { App } from "./app";import "@canva/app-ui-kit/styles.css";const root = createRoot(document.getElementById("root") as Element);function render() {root.render(<AppUiProvider><App /></AppUiProvider>,);}render();if (module.hot) {module.hot.accept("./app", render);}
TYPESCRIPT
// Import testing sub-packagesimport * as asset from "@canva/asset/test";import * as design from "@canva/design/test";import * as error from "@canva/error/test";import * as platform from "@canva/platform/test";import * as user from "@canva/user/test";// Initialize the test environmentsasset.initTestEnvironment();design.initTestEnvironment();error.initTestEnvironment();platform.initTestEnvironment();user.initTestEnvironment();// Once they're initialized, mock the SDKsjest.mock("@canva/asset");jest.mock("@canva/design");jest.mock("@canva/platform");jest.mock("@canva/user");// n.b. @canva/error should not be mocked - use it to simulate API error responses from other mocks by throwing CanvaError
TYPESCRIPT
import { TestAppUiProvider } from "@canva/app-ui-kit";import type { RenderResult } from "@testing-library/react";import { fireEvent, render, within } from "@testing-library/react";import { openColorSelector } from "@canva/asset";import { features, requestOpenExternalUrl } from "@canva/platform";import { API_URL, App, DOCS_URL, QUOTA_ERROR } from "../app";import { addPage } from "@canva/design";import { CanvaError } from "@canva/error";function renderInTestProvider(node: React.ReactNode): RenderResult {return render(// In a test environment, you should wrap your apps in `TestAppUiProvider`, rather than `AppUiProvider`// Refer to the i18n example for information on how to test with localization<TestAppUiProvider>{node}</TestAppUiProvider>,);}describe("Example Tests", () => {// These functions have already been mocked in jest.setup.ts, this is just for type castingconst mockRequestOpenExternalUrl = jest.mocked(requestOpenExternalUrl);const mockIsSupported = jest.mocked(features.isSupported);const mockAddPage = jest.mocked(addPage);beforeEach(() => {jest.resetAllMocks();mockRequestOpenExternalUrl.mockResolvedValue({ status: "completed" });mockIsSupported.mockReturnValue(true);});// this test demonstrates basic assertions for whether or not a Canva App API function was calledit("should call `openColorSelector` when the swatch is clicked", () => {// assert that the mock is in the expected clean stateexpect(openColorSelector).not.toHaveBeenCalled();const result = renderInTestProvider(<App />);// get a reference to the button element by looking within the color-selector div for the button roleconst colorSelectorDiv = result.container.querySelector("#color-selector",) as HTMLElement;const swatch = within(colorSelectorDiv).getByRole("button");// confirm that our callback has not been called in the initial renderexpect(openColorSelector).not.toHaveBeenCalled();// programmatically simulate clicking the buttonfireEvent.click(swatch);// we expect that openColorSelector has been called by the button's click handlerexpect(openColorSelector).toHaveBeenCalled();});// this test demonstrates assertions for the arguments passed to a Canva App API function across multiple callsit("should call `requestOpenExternalUrl` when the button is clicked", () => {expect(mockRequestOpenExternalUrl).not.toHaveBeenCalled();const result = renderInTestProvider(<App />);// get a reference to the Apps SDK button by nameconst sdkButton = result.getByRole("button", {name: "Apps SDK",});expect(mockRequestOpenExternalUrl).not.toHaveBeenCalled();fireEvent.click(sdkButton);expect(mockRequestOpenExternalUrl).toHaveBeenCalled();// assert that the requestOpenExternalUrl function was called with the expected argumentsexpect(mockRequestOpenExternalUrl.mock.calls[0][0]).toEqual({url: DOCS_URL,});// the name property of the getByRole query can be a regex to match partial contents of the button labelconst referenceButton = result.getByRole("button", {name: /Reference/,});fireEvent.click(referenceButton);expect(mockRequestOpenExternalUrl).toHaveBeenCalledTimes(2);expect(mockRequestOpenExternalUrl.mock.calls[1][0]).toEqual({url: API_URL,});});// the addPage function is not supported in all design types, so we need to test how the app handles this// the next three tests demonstrate the permutations - when it is supported , when it is not supported, and when it is supported but throws an errorit("should show a button when `addPage` is supported and call it when the button is clicked", () => {const result = renderInTestProvider(<App />);const addPageButton = result.getByRole("button", {name: "Add Page",});// assert the button was foundexpect(addPageButton).toBeDefined();expect(addPage).not.toHaveBeenCalled();fireEvent.click(addPageButton);expect(addPage).toHaveBeenCalled();});it("should show a message when `addPage` is not supported", () => {mockIsSupported.mockReturnValue(false);const result = renderInTestProvider(<App />);const text = result.getByText(/Adding pages is not supported/);expect(text).toBeDefined();// the button should not be rendered, so getByRole should throw an errorexpect(() => result.getByRole("button", { name: "Add Page" })).toThrow();});it("should show an error message when `addPage` throws an error", async () => {mockAddPage.mockImplementationOnce(() => {throw new CanvaError({code: "quota_exceeded",message: "Quota exceeded",});});const result = renderInTestProvider(<App />);const addPageButton = result.getByRole("button", {name: "Add Page",});fireEvent.click(addPageButton);expect(mockAddPage).toHaveBeenCalled();// assert that the error message is displayed after the error was caughtconst errorMessage = result.getByText(QUOTA_ERROR);expect(errorMessage).toBeDefined();});});
TYPESCRIPT
# Unit testingDemonstrates how to structure app logic for unit testing, including testable functions, error handling, and API interaction patterns. Shows separation of concerns for better testability.For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/examples/unit-test/.Related example: See testing/ui_test for testing UI components separately from business logic.NOTE: This example differs from what is expected for public apps to pass a Canva review:- Error handling is simplified for demonstration. Production apps must implement comprehensive error handling with clear user feedback and graceful failure modes- Internationalization is not implemented. Production apps must support multiple languages using the `@canva/app-i18n-kit` package to pass Canva review requirements
MARKDOWN
API Reference
Need Help?
- Join our Community Forum(opens in a new tab or window)
- Report issues with this example on GitHub(opens in a new tab or window)