> ## Documentation Index > Fetch the complete documentation index at: https://www.canva.dev/docs/apps/llms.txt > Use this file to discover all available pages before exploring further. # Unit test Unit testing Apps SDK packages. ## Running this example To run this example locally: 1. If you haven't already, create a new app in the [Developer Portal](https://www.canva.com/developers/apps). For more information, refer to our [Quickstart guide](https://www.canva.dev/docs/apps/quickstart/). 2. In your app's configuration on the [Developer Portal](https://www.canva.com/developers/apps), ensure the "Development URL" is set to `http://localhost:8080`. 3. Clone the starter kit: ```shell git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.git cd canva-apps-sdk-starter-kit ``` 4. Install dependencies: ```shell npm install ``` 5. Run the example: ```shell npm run start:example unit_test ``` 6. Click the **Preview URL** link shown in the terminal to open the example in the Canva editor. ## Example app source code ```typescript // 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 "@canva/app-hooks"; 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(); const [color, setColor] = useState(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; // Handle other error types - you may want to customize error messages default: setError(e.message); break; } } } }; const isSupported = useFeatureSupport(); const canAddPage = isSupported(addPage); return (
{error && {error}} {/* === This swatch is used in the unit test to demonstrate listening for calls to a Canva Apps API */}
Color Selector handleSwatchClick(e.currentTarget.getBoundingClientRect()) } />
{/* === These buttons are used in the unit test to demonstrate checking for parameters passed to Canva Apps APIs === */} Open External Link {/* === Displaying this section is contingent on the feature being supported - this can be mocked in a unit test to check both paths */} Add Page {canAddPage ? ( ) : ( Adding pages is not supported in this design. Please try this example in a different design. )}
); }; ```
```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"; import type { DesignEditorIntent } from "@canva/intents/design"; import { prepareDesignEditor } from "@canva/intents/design"; async function render() { const root = createRoot(document.getElementById("root") as Element); root.render( , ); } const designEditor: DesignEditorIntent = { render }; prepareDesignEditor(designEditor); // Hot Module Replacement for development (automatically reloads the app when changes are made) if (module.hot) { module.hot.accept("./app", render); } ``` ```typescript // For usage information, see the README.md file. // Import Canva SDK testing utilities import * as asset from "@canva/asset/test"; import * as design from "@canva/design/test"; import * as error from "@canva/error/test"; import * as intents from "@canva/intents/test"; import * as platform from "@canva/platform/test"; import * as user from "@canva/user/test"; /* Initialize test environments for each Canva SDK package This sets up the necessary test infrastructure before mocking the actual SDK methods */ asset.initTestEnvironment(); design.initTestEnvironment(); error.initTestEnvironment(); intents.initTestEnvironment(); platform.initTestEnvironment(); user.initTestEnvironment(); /* Mock all Canva SDK packages except @canva/error This allows tests to run without making real API calls to Canva's services */ jest.mock("@canva/asset"); jest.mock("@canva/design"); jest.mock("@canva/intents"); jest.mock("@canva/platform"); jest.mock("@canva/user"); /* Important: @canva/error should not be mocked Use it to simulate API error responses from other mocks by throwing CanvaError instances This allows testing of error handling scenarios */ ``` ```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 {node}, ); } describe("Example Tests", () => { // These functions have already been mocked in jest.setup.ts, this is just for type casting const 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 called it("should call `openColorSelector` when the swatch is clicked", () => { // assert that the mock is in the expected clean state expect(openColorSelector).not.toHaveBeenCalled(); const result = renderInTestProvider(); // get a reference to the button element by looking within the color-selector div for the button role const 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 render expect(openColorSelector).not.toHaveBeenCalled(); // programmatically simulate clicking the button fireEvent.click(swatch); // we expect that openColorSelector has been called by the button's click handler expect(openColorSelector).toHaveBeenCalled(); }); // this test demonstrates assertions for the arguments passed to a Canva App API function across multiple calls it("should call `requestOpenExternalUrl` when the button is clicked", () => { expect(mockRequestOpenExternalUrl).not.toHaveBeenCalled(); const result = renderInTestProvider(); // get a reference to the Apps SDK button by name const 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 arguments expect(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 label const 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 error it("should show a button when `addPage` is supported and call it when the button is clicked", () => { const result = renderInTestProvider(); const addPageButton = result.getByRole("button", { name: "Add Page", }); // assert the button was found expect(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(); const text = result.getByText(/Adding pages is not supported/); expect(text).toBeDefined(); // the button should not be rendered, so getByRole should throw an error expect(() => 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(); 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 caught const errorMessage = result.getByText(QUOTA_ERROR); expect(errorMessage).toBeDefined(); }); }); ``` ```markdown # Unit testing Demonstrates 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 - The code structure is simplified: Production apps using [intents](https://www.canva.dev/docs/apps/intents/) are recommended to call the prepareDesignEditor function from src/intents/design_editor/index.tsx ```
## API reference * [App UI Kit](https://www.canva.dev/docs/apps/app-ui-kit/) * [Unit testing](https://www.canva.dev/docs/apps/testing/) * [`addPage`](https://www.canva.dev/docs/apps/api/latest/design-add-page/) * [`features.isSupported`](https://www.canva.dev/docs/apps/api/latest/platform-features-is-supported/) * [`openColorSelector`](https://www.canva.dev/docs/apps/api/latest/asset-open-color-selector/) * [`prepareDesignEditor`](https://www.canva.dev/docs/apps/api/latest/intents-design-prepare-design-editor/) * [`requestOpenExternalUrl`](https://www.canva.dev/docs/apps/api/latest/platform-request-open-external-url/) ## Need help? * Join our [Community Forum](https://community.canva.dev/) * Report issues with this example on [GitHub](https://github.com/canva-sdks/canva-apps-sdk-starter-kit/issues)