Salla Docs
Merchant API
  • Merchant API
  • Salla OAuth 2.0
Partner APIs
  • App API
  • Shipments & Fulfillment APIs
  • Recurring Payments API
  • App Functions
Storefront
  • Twilight Engine
  • Twilight SDK
  • Web Components
  • Change Log
Salla CLI
Merchant API
  • Merchant API
  • Salla OAuth 2.0
Partner APIs
  • App API
  • Shipments & Fulfillment APIs
  • Recurring Payments API
  • App Functions
Storefront
  • Twilight Engine
  • Twilight SDK
  • Web Components
  • Change Log
Salla CLI
Salla - Opensource
Salla - Developers Community
  1. App Functions
  • Welcome 👋
  • What are App Functions?
  • Get Started
  • Supported Events
  • Testing
  • Responses
  • NodeJs Support
  • Merchants Events
    • Brand Events
    • Cart Events
    • Category Events
    • Communication Events
    • Customer Events
    • Invoice Events
    • Review Events
    • Shipment Events
    • Shipping Company Events
    • Shipping Zone Events
    • Special Offer Events
    • Store Branch Events
  • Customers Events
    • Account Events
    • Cart & Checkout Events
    • Product Events
    • Promotion & Coupon Events
    • Wishlist Events
  1. App Functions

Testing

Testing your App Functions is crucial to ensure they work correctly before deploying to production. This guide covers everything you need to know about testing your functions effectively.


Overview

Salla provides built-in testing tools directly in the Partner Portal, allowing you to:

  • 🧪 Test functions with real store data
  • 👁️ Preview function responses in real-time
  • 🐛 Debug issues before deployment
  • ✔️ Validate API integrations
  • 🔍 Inspect context data structures

Testing Environment

Prerequisites

Before testing your App Functions, ensure:

  • ✔️ Demo Store Setup — Your app is installed on a demo store
  • ✔️ App Scopes Configured — Required permissions are set
  • ✔️ Test Data Available — Demo store has relevant data (orders, products, etc.)
  • ✔️ External Services Ready — Any external APIs or webhooks are accessible

Accessing the Test Environment

  1. 🔐 Log in to Salla Partner Portal
  2. 📱 Navigate to your app
  3. 📋 Scroll to the App Functions section
  4. ✔️ Select the function you want to test
  5. 👁️ The test panel appears on the right side of the editor

Testing Your Functions

Step 1: Select a Demo Store

Click Select Store in the preview panel and choose your demo store from the dropdown.

Select Store

**Multiple Stores**: If you have multiple demo stores, you can test against different configurations to ensure your function works in various scenarios.

Step 2: Prepare Test Data

Navigate to your demo store dashboard to get the required test data:

  • 📦 For Order Events: Get an Order ID
  • 🛍️ For Product Events: Get a Product ID
  • 👤 For Customer Events: Get a Customer ID
  • 📋 For Other Events: Get relevant entity IDs

Demo Store Dashboard

Step 3: Enter Test Parameters

Enter the required parameters in the preview panel. For example, if testing an Order Status Updated function, enter the Order ID.

Enter Order ID

**Event-Specific Parameters**: Different events require different parameters. The preview panel will show you what's needed for each event type.

Step 4: Execute and Review

Click Save and Preview to execute your function with the test data.

Save and Preview

The preview panel will display:

  • ✔️ Execution Status — Success or failure

  • 📦 Response Data — The data returned by your function

  • ⏱️ Execution Time — How long the function took to run

  • 📝 Console Logs — Any console.log() output from your function

  • ❌ Errors — Any errors that occurred during execution


Inspecting Context Data

Understanding the context object structure is essential for writing effective functions.

Viewing Context Schema

To view the expected context structure for your function:

Right-click on the context parameter in your function signature.

Context Menu

Choose Peek > Peek Definition from the context menu.

Peek Definition

View the complete context structure including all available properties and their types.

Context Structure

Scroll through to see:

  • 📦 Payload structure

  • 📋 Event-specific data fields

  • ⚙️ Settings object

  • 🏪 Merchant information

  • 💻 Type definitions


Testing API Integrations

When your function calls Salla APIs or external services, follow these best practices:

Testing Salla API Calls

export default async (
  context: OrderCreatedContext
): Promise<Resp> => {
  // Test accessing Salla API with automatic authentication
  // NOTE: Authorization header is automatically injected.
  const response = await fetch("https://api.salla.dev/admin/v2/orders", {
    method: "GET",
  });

  const orders = await response.json();

  // Log for debugging (visible in preview panel)
  console.log("Fetched orders count:", orders.data?.length);

  const data = { 
    total_orders: orders.data?.length,
      first_order: orders.data?.[0],
  };
  /*
    * The .setData() should be called mandatorily. (Pass {} as default)
    * The .setStatus() is optionallly called. The default status is 200.
    * The .setMessage() is optional. 
    * Incase there is any error invoke Resp.error().
  */
  const response = Resp.success().setData(data)

  return response;
};
**Automatic Authentication**: You can access Salla APIs with automatic token injection. No need to manually handle authentication when coding inside the Partner Portal.

Testing External API Calls

export default async (
  context: OrderStatusUpdatedContext
): Promise<Resp> => {
  try {
    const { payload, settings, merchant } = context;

    // Test external webhook
    const webhookResponse = await fetch(settings.webhookUrl, {
      // URL from app settings
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${settings.apiKey}`, // API key from app settings
      },
      body: JSON.stringify({
        order_id: payload.data.id,
        status: payload.data.status,
        timestamp: new Date().toISOString(),
      }),
    });

    // Log response for debugging
    console.log("Webhook status:", webhookResp.status);
    console.log("Webhook response:", await webhookResp.text());

    const data = { 
      webhook_status: webhookResp.status
    };
    /*
      * The .setData() should be called mandatorily. (Pass {} as default)
      * The .setStatus() is optionallly called. The default status is 200.
      * The .setMessage() is optional. 
      * Incase there is any error invoke Resp.error().
    */
    const response = Resp.success().setData(data)

    return response;
  } catch (error) {
    console.error('Error sending webhook:', error);
    return Resp.error()
      .setMessage(error.message || 'Unknown error')
      .setStatus(500)
      .setData({ error_type: error.name });
  }
};

Best Practices for Testing

1. Test Multiple Scenarios

Test your function with different types of data:

  • ✔️ Happy Path: Normal, expected data
  • ⚠️ Edge Cases: Empty values, null fields, minimum/maximum values
  • ❌ Error Cases: Invalid data, API failures, timeouts
  • 🔄 Different States: Various order statuses, product types, etc.

2. Use Meaningful Logs

Add console.log statements to track execution flow:

console.log("Function started for order:", context.payload.data.id);
console.log("Calling external API...");
console.log("API response received:", response.status);
console.log("Function completed successfully");
**Avoid Logging Sensitive Data**: Never log sensitive information like:
  • ❌ API keys or tokens
  • ❌ Customer personal data
  • ❌ Payment information
  • ❌ Passwords or credentials

3. Return Consistent Responses

Always return a structured response object:

// Success response
return Resp.success().setData({
    // Relevant data
});


// Error response
return Resp.error()
    .setMessage("Descriptive error message")
    .setStatus(500)
    .setData({
      // Additional error context
});

4. Handle Errors Gracefully

Use try-catch blocks and provide meaningful error messages:

try {
  // Your logic
} catch (error) {
  console.error("Error details:", error);
  return Resp.error()
      .setMessage(error.message || 'Unknown error')
      .setStatus(500)
      .setData({ error_type: error.name });
}

5. Validate Input Data

Check that required data exists before using it:

export default async (
  context: OrderCreatedContext
): Promise<Resp> => {
  const { payload, settings, merchant } = context;

  // Validate required data
  if (!payload.data?.id) {
    return Resp.error()
      .setMessage('Order ID is missing')
      .setStatus(400)
      .setData({});
  }

  if (!settings.webhookUrl) {
    return Resp.error()
      .setMessage('Webhook URL not configured in settings')
      .setStatus(400)
      .setData({});
  }

  // Continue with logic...
};

6. Test Response Size

Keep response objects small and focused:

// ❌ Bad: Returning entire payload
return Resp.success().setData({
    data: context.payload
});

// ✅ Good: Returning only relevant data
return Resp.success().setData({
    order_id: context.payload.data.id,
    status: context.payload.data.status,
    processed_at: new Date().toISOString(),
});
**Response Size**: If the response is too large, log only key fields. The preview window works best with concise responses.

Testing External Webhooks

When testing functions that call external webhooks:

Using Webhook Testing Services

  1. 🔗 Create a test webhook at webhook.site or similar service
  2. 📋 Copy the webhook URL to your app settings
  3. ▶️ Run your function in the preview panel
  4. ✔️ Check the webhook site to verify the payload was received

Example Webhook Test

export default async (
  context: OrderCreatedContext
): Promise<Resp> => {
  try {
    const webhookUrl = "https://webhook.site/your-unique-id";

    const response = await fetch(webhookUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        event: context.payload.event,
        order_id: context.payload.data.id,
        merchant_id: context.payload.merchant.id,
        timestamp: new Date().toISOString(),
      }),
    });

    console.log("Webhook called successfully:", response.status);

    return Resp.success().setData({
        webhook_status: response.status,
    });
  } catch (error) {
    return Resp.error()
      .setMessage(error.message)
      .setStatus(400)
      .setData({});
  }
};

Debugging Common Issues

Issue: Function Times Out

Possible Causes:

  • 🐌 External API is slow or unresponsive
  • 🔄 Infinite loops in code
  • 📦 Large data processing
  • ⚠️ For Synchronous Actions: Function is too slow (user is waiting!)

Solutions:

  • ⏱️ Add timeout to fetch calls
  • ⚡ Optimize data processing
  • 🔄 Use async operations efficiently
  • ⚠️ For Synchronous Actions: Keep logic extremely simple and fast (< 500ms)
// Add timeout to fetch
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000); // 5 second timeout

try {
  const response = await fetch(url, {
    signal: controller.signal, // Links the fetch request to the abort controller
  });
  clearTimeout(timeout);
} catch (error) {
  if (error.name === "AbortError") {
    console.error("Request timed out");
  }
}
**Synchronous Actions Performance**: If you're testing a **synchronous action** (e.g., `shipment.creating`), remember that the user is blocked and waiting. Your function must respond in **milliseconds** (< 500ms recommended). Avoid:
  • ❌ Slow external API calls
  • ❌ Complex calculations
  • ❌ Database queries
  • ❌ Multiple sequential requests

Keep synchronous actions simple and fast!

Issue: Context Data is Undefined

Possible Causes:

  • ❌ Incorrect event type selected
  • ❌ Test data doesn't exist in demo store
  • ❌ Wrong parameter passed

Solutions:

  • ✔️ Verify event type matches your function
  • ✔️ Check demo store has the required data
  • ✔️ Validate test parameters

Issue: API Calls Fail

Possible Causes:

  • ❌ Incorrect API endpoint
  • ❌ Missing app scopes
  • ❌ Invalid request format

Solutions:

  • ✔️ Verify API endpoint URL
  • ✔️ Check app scopes in Partner Portal
  • ✔️ Review API documentation
  • ✔️ Check request headers and body format

Publishing After Testing

Once you've thoroughly tested your function:

  1. ✔️ Review all test results to ensure everything works as expected
  2. ⚠️ Test edge cases and error scenarios
  3. 🔌 Verify external integrations are working correctly
  4. 📝 Check console logs for any warnings or errors
  5. 🚀 Return to Partner Portal and publish your changes
**Sandbox vs Production**: All changes are saved in the sandbox environment until you publish. Always test thoroughly before publishing to production.

Next Steps

  • 💻 Event Schemas — View detailed schemas for all events
  • 🚀 Quick Start — Create your first App Function
  • 📋 Supported Events — Explore all available events
  • 📚 Salla APIs — API documentation and reference
Modified at 2025-11-17 11:41:06
Previous
Supported Events
Next
Responses