Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add E2E tests for SDK against a live Rails app
Damian Legawiec5e8f1324b80c
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.ymlindex 71d0e4f302..c3dfa3af53 100644--- a/.github/workflows/packages.yml+++ b/.github/workflows/packages.yml@@ -5,6 +5,8 @@ on:branches: [main]paths:- "packages/**"+ - "spree/api/app/**"+ - "spree/core/app/**"- "docs/developer/**"- "docs/api-reference/**"- "docs/integrations/**"@@ -14,6 +16,8 @@ on:pull_request:paths:- "packages/**"+ - "spree/api/app/**"+ - "spree/core/app/**"- "docs/developer/**"- "docs/api-reference/**"- "docs/integrations/**"@@ -46,6 +50,41 @@ jobs:- run: pnpm turbo typecheck test build+ sdk-integration:+ name: "SDK Integration Tests"+ runs-on: ubuntu-latest+ env:+ RAILS_ENV: test+ DB: sqlite3+ steps:+ - uses: actions/checkout@v4++ - uses: ruby/setup-ruby@v1+ with:+ ruby-version: '4.0'+ bundler-cache: true+ working-directory: spree/api++ - uses: pnpm/action-setup@v4++ - uses: actions/setup-node@v4+ with:+ node-version: 20+ cache: pnpm++ - run: pnpm install --frozen-lockfile++ - name: Build SDK dependencies+ run: pnpm turbo build --filter=@spree/sdk-core++ - name: Setup test app+ working-directory: spree/api+ run: bundle exec rake test_app++ - name: Run SDK integration tests+ working-directory: packages/sdk+ run: pnpm test:integration+release-sdk:name: "SDK - Release"needs: checkdiff --git a/packages/sdk/.gitignore b/packages/sdk/.gitignoreindex dd6e803c7f..9d9369109d 100644--- a/packages/sdk/.gitignore+++ b/packages/sdk/.gitignore@@ -2,3 +2,4 @@ node_modules/dist/*.log.DS_Store+tests/integration/.credentials.jsondiff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 544075ada2..a3ec8e60f9 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -49,6 +49,7 @@"console": "tsx console.ts","typecheck": "tsc --noEmit","test": "vitest run",+ "test:integration": "vitest run --config vitest.integration.config.ts","test:watch": "vitest","test:coverage": "vitest run --coverage","clean": "rm -rf dist",diff --git a/packages/sdk/tests/integration/auth.test.ts b/packages/sdk/tests/integration/auth.test.tsnew file mode 100644index 0000000000..3a740af84b--- /dev/null+++ b/packages/sdk/tests/integration/auth.test.ts@@ -0,0 +1,32 @@+import { describe, it, expect } from 'vitest';+import { client } from './helpers';+import { getCredentials } from './setup';++describe('auth', () => {+ it('logs in with email/password and returns JWT', async () => {+ const creds = getCredentials();+ const result = await client().auth.login({+ email: creds.user_email,+ password: creds.user_password,+ });++ expect(result.token).toBeDefined();+ expect(result.refresh_token).toBeDefined();+ expect(result.user.email).toBe(creds.user_email);+ });++ it('refreshes a token', async () => {+ const creds = getCredentials();+ const login = await client().auth.login({+ email: creds.user_email,+ password: creds.user_password,+ });++ const result = await client().auth.refresh({+ refresh_token: login.refresh_token,+ });++ expect(result.token).toBeDefined();+ expect(result.token).not.toBe(login.token);+ });+});diff --git a/packages/sdk/tests/integration/cart.test.ts b/packages/sdk/tests/integration/cart.test.tsnew file mode 100644index 0000000000..ff4f7450bf--- /dev/null+++ b/packages/sdk/tests/integration/cart.test.ts@@ -0,0 +1,105 @@+import { describe, it, expect } from 'vitest';+import { client, buildCart } from './helpers';++describe('cart items', () => {+ it('creates a cart, adds item, updates, removes', async () => {+ const c = client();++ const products = await c.products.list();+ const variantId = products.data.find(p => p.purchasable && p.default_variant_id)!.default_variant_id;++ const cart = await c.carts.create();+ expect(cart.id).toMatch(/^cart_/);+ expect(cart.token).toBeDefined();+ expect(cart).toHaveProperty('items');+ expect(cart).toHaveProperty('fulfillments');+ expect(cart).toHaveProperty('payment_methods');+ expect(cart).toHaveProperty('payments');++ const opts = { spreeToken: cart.token };++ const updated = await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 2 }, opts);+ expect(updated.items.length).toBe(1);+ expect(updated.items[0].quantity).toBe(2);++ const lineItemId = updated.items[0].id;+ const after = await c.carts.items.update(cart.id, lineItemId, { quantity: 1 }, opts);+ expect(after.items[0].quantity).toBe(1);++ const empty = await c.carts.items.delete(cart.id, lineItemId, opts);+ expect(empty.items.length).toBe(0);+ });+});++describe('cart addresses', () => {+ it('sets shipping and billing addresses', async () => {+ const { cart } = await buildCart('address');++ expect(cart.shipping_address).toBeDefined();+ expect(cart.billing_address).toBeDefined();+ expect(cart.email).toBeDefined();+ });+});++describe('cart fulfillments', () => {+ it('selects a delivery rate', async () => {+ const { cart } = await buildCart('delivery');++ expect(Number(cart.delivery_total)).toBeGreaterThan(0);+ });+});++describe('cart payment sessions', () => {+ it('creates and gets a payment session', async () => {+ const { c, cart, opts, creds } = await buildCart('delivery');++ const session = await c.carts.paymentSessions.create(cart.id, {+ payment_method_id: creds.bogus_payment_method_id,+ }, opts);++ expect(session.id).toMatch(/^ps_/);+ expect(session.status).toBe('pending');+ expect(session.payment_method_id).toBe(creds.bogus_payment_method_id);++ const fetched = await c.carts.paymentSessions.get(cart.id, session.id, opts);+ expect(fetched.id).toBe(session.id);+ });++ it('completes a payment session', async () => {+ const { c, cart, opts, session } = await buildCart('payment');++ const completed = await c.carts.paymentSessions.complete(cart.id, session!.id, undefined, opts);+ expect(completed.status).toBe('completed');+ });+});++describe('cart completion', () => {+ it('completes cart with Check payment and returns order', async () => {+ const { c, cart, opts, creds } = await buildCart('delivery');++ const payment = await c.carts.payments.create(cart.id, {+ payment_method_id: creds.check_payment_method_id,+ }, opts);+ expect(payment.id).toMatch(/^py_/);++ const order = await c.carts.complete(cart.id, opts);++ expect(order.id).toMatch(/^or_/);+ expect(order.number).toBeDefined();+ expect(order.completed_at).toBeDefined();+ expect(order.payment_status).toBeDefined();+ expect(order.items.length).toBeGreaterThan(0);+ });++ it('gets a completed order as guest via spree token', async () => {+ const { c, cart, opts, creds } = await buildCart('delivery');+ await c.carts.payments.create(cart.id, { payment_method_id: creds.check_payment_method_id }, opts);+ const order = await c.carts.complete(cart.id, opts);++ const fetched = await c.orders.get(order.id, undefined, opts);++ expect(fetched.id).toBe(order.id);+ expect(fetched.number).toBe(order.number);+ expect(fetched.completed_at).toBeDefined();+ });+});diff --git a/packages/sdk/tests/integration/catalog.test.ts b/packages/sdk/tests/integration/catalog.test.tsnew file mode 100644index 0000000000..4132c19619--- /dev/null+++ b/packages/sdk/tests/integration/catalog.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest';+import { client } from './helpers';+import { getCredentials } from './setup';++describe('products', () => {+ it('lists products with correct shape', async () => {+ const result = await client().products.list();++ expect(result.data).toBeInstanceOf(Array);+ expect(result.data.length).toBeGreaterThan(0);+ expect(result.meta).toHaveProperty('count');++ const product = result.data[0];+ expect(product.id).toMatch(/^prod_/);+ expect(product).toHaveProperty('name');+ expect(product).toHaveProperty('slug');+ expect(product).toHaveProperty('price');+ expect(product).toHaveProperty('purchasable');+ expect(product).toHaveProperty('in_stock');+ });++ it('gets a product by slug', async () => {+ const creds = getCredentials();+ const product = await client().products.get(creds.product_slug);++ expect(product.id).toBe(creds.product_id);+ expect(product.slug).toBe(creds.product_slug);+ });++ it('returns product filters', async () => {+ const result = await client().products.filters();++ expect(result).toHaveProperty('filters');+ expect(result).toHaveProperty('sort_options');+ });+});++describe('categories', () => {+ it('lists categories', async () => {+ const result = await client().categories.list();++ expect(result.data).toBeInstanceOf(Array);+ expect(result.data.length).toBeGreaterThan(0);++ const category = result.data[0];+ expect(category.id).toMatch(/^ctg_/);+ expect(category).toHaveProperty('name');+ expect(category).toHaveProperty('permalink');+ });+});diff --git a/packages/sdk/tests/integration/customer.test.ts b/packages/sdk/tests/integration/customer.test.tsnew file mode 100644index 0000000000..0d3aaab9f6--- /dev/null+++ b/packages/sdk/tests/integration/customer.test.ts@@ -0,0 +1,120 @@+import { describe, it, expect } from 'vitest';+import { client, authOpts } from './helpers';+import { getCredentials } from './setup';++describe('customer profile', () => {+ it('gets current customer profile', async () => {+ const customer = await client().customer.get(authOpts());++ expect(customer.email).toBe(getCredentials().user_email);+ expect(customer).toHaveProperty('first_name');+ expect(customer).toHaveProperty('last_name');+ });+});++describe('customer addresses', () => {+ it('creates an address and lists with is_default fields', async () => {+ await client().customer.addresses.create({+ first_name: 'List',+ last_name: 'Test',+ address1: '50 Wall St',+ city: 'New York',+ postal_code: '10005',+ country_iso: 'US',+ state_abbr: 'NY',+ }, authOpts());++ const result = await client().customer.addresses.list(undefined, authOpts());++ expect(result.data.length).toBeGreaterThan(0);+ const address = result.data[0];+ expect(address.id).toMatch(/^addr_/);+ expect(address).toHaveProperty('is_default_billing');+ expect(address).toHaveProperty('is_default_shipping');+ expect(typeof address.is_default_billing).toBe('boolean');+ expect(typeof address.is_default_shipping).toBe('boolean');+ });++ it('creates an address with is_default_billing', async () => {+ const address = await client().customer.addresses.create({+ first_name: 'Integration',+ last_name: 'Test',+ address1: '100 Broadway',+ city: 'New York',+ postal_code: '10005',+ country_iso: 'US',+ state_abbr: 'NY',+ is_default_billing: true,+ }, authOpts());++ expect(address.id).toMatch(/^addr_/);+ expect(address.is_default_billing).toBe(true);+ expect(address.city).toBe('New York');+ });++ it('updates an address and sets default shipping', async () => {+ const created = await client().customer.addresses.create({+ first_name: 'Update',+ last_name: 'Test',+ address1: '200 Park Ave',+ city: 'New York',+ postal_code: '10166',+ country_iso: 'US',+ state_abbr: 'NY',+ }, authOpts());++ const updated = await client().customer.addresses.update(+ created.id,+ { is_default_shipping: true, city: 'Brooklyn' },+ authOpts()+ );++ expect(updated.id).toBe(created.id);+ expect(updated.is_default_shipping).toBe(true);+ expect(updated.city).toBe('Brooklyn');+ });+});++describe('customer orders', () => {+ it('completes an order and lists/views it in order history', async () => {+ const creds = getCredentials();+ const c = client();++ const products = await c.products.list();+ const variantId = products.data.find(p => p.purchasable && p.default_variant_id)!.default_variant_id;++ const cart = await c.carts.create(undefined, authOpts());+ const opts = { ...authOpts(), spreeToken: cart.token };++ await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 1 }, opts);++ const address = {+ first_name: 'Order', last_name: 'History',+ address1: '1 Times Square', city: 'New York', postal_code: '10036',+ country_iso: creds.country_iso, state_abbr: 'NY', phone: '555-0100',+ };+ const withAddr = await c.carts.update(cart.id, {+ email: creds.user_email,+ shipping_address: address,+ billing_address: address,+ }, opts);++ const ful = withAddr.fulfillments[0];+ await c.carts.fulfillments.update(cart.id, ful.id, { selected_delivery_rate_id: ful.delivery_rates[0].id }, opts);+ await c.carts.payments.create(cart.id, { payment_method_id: creds.check_payment_method_id }, opts);+ const order = await c.carts.complete(cart.id, opts);++ // List+ const orders = await c.customer.orders.list(undefined, authOpts());+ expect(orders.data.length).toBeGreaterThan(0);+ const found = orders.data.find(o => o.id === order.id);+ expect(found).toBeDefined();+ expect(found!.number).toBe(order.number);++ // Detail+ const detail = await c.customer.orders.get(order.id, undefined, authOpts());+ expect(detail.id).toBe(order.id);+ expect(detail.completed_at).toBeDefined();+ expect(detail.items.length).toBeGreaterThan(0);+ });+});diff --git a/packages/sdk/tests/integration/global-setup.ts b/packages/sdk/tests/integration/global-setup.tsnew file mode 100644index 0000000000..6f88bc846c--- /dev/null+++ b/packages/sdk/tests/integration/global-setup.ts@@ -0,0 +1,79 @@+/**+ * Global setup — runs once before all integration test files.+ * Seeds the database, boots a Rails server, and provides credentials.+ */+import { execSync, spawn, type ChildProcess } from 'child_process';+import { resolve } from 'path';+import { writeFileSync } from 'fs';+import type { GlobalSetupContext } from 'vitest/node';++const API_GEM_DIR = resolve(__dirname, '../../../../spree/api');+const RAILS = 'bundle exec spec/dummy/bin/rails';+const PORT = process.env.INTEGRATION_PORT || '3010';+const CREDENTIALS_FILE = resolve(__dirname, '.credentials.json');++const execOpts = { cwd: API_GEM_DIR, encoding: 'utf-8' as const, timeout: 120_000, maxBuffer: 10 * 1024 * 1024, env: { ...process.env, RAILS_ENV: 'test', PORT } };++const CREDENTIALS_RUBY = [+ 'require "json"',+ 's = Spree::Store.default',+ 'k = s.api_keys.active.publishable.first',+ 'pm = Spree::Gateway::Bogus.where(name: "Credit Card (Test)").first_or_create!(stores: [s], active: true, display_on: "both")',+ 'check = Spree::PaymentMethod::Check.where(name: "Check (Test)").first_or_create!(stores: [s], active: true, display_on: "both")',+ 'u = Spree.user_class.where.not(email: nil).where("email NOT LIKE ?", "%@spree.com").first',+ 'u.update!(password: "spree123", password_confirmation: "spree123")',+ 'sec = Spree::Api::Config[:jwt_secret_key].presence || Rails.application.credentials.jwt_secret_key || ENV["JWT_SECRET_KEY"] || Rails.application.secret_key_base',+ 'jwt = JWT.encode({ user_id: u.id, user_type: "customer", jti: SecureRandom.uuid, iss: "spree", aud: "store_api", exp: 1.hour.from_now.to_i }, sec, "HS256")',+ 'p = s.products.available.first',+ 'c = s.taxonomies.first&.root&.children&.first',+ 'port = ENV.fetch("PORT", 3010)',+ 'puts JSON.generate(base_url: "http://localhost:#{port}", publishable_key: k.token, jwt_token: jwt, user_email: u.email, user_password: "spree123", product_slug: p&.slug, product_id: p&.prefixed_id, variant_id: p&.default_variant&.prefixed_id, category_id: c&.prefixed_id, category_permalink: c&.permalink, country_iso: "US", store_name: s.name, bogus_payment_method_id: pm.prefixed_id, check_payment_method_id: check.prefixed_id)',+].join('; ');++let serverProcess: ChildProcess | null = null;++function waitForServer(url: string, timeoutMs = 30_000): Promise<void> {+ const start = Date.now();+ return new Promise((resolve, reject) => {+ const check = async () => {+ try {+ const res = await fetch(url);+ if (res.ok || res.status === 401) { resolve(); return; }+ } catch { /* not ready */ }+ if (Date.now() - start > timeoutMs) { reject(new Error(`Server did not start within ${timeoutMs}ms`)); return; }+ setTimeout(check, 500);+ };+ check();+ });+}++export async function setup() {+ // 1. Seed + load sample data+ execSync(`${RAILS} runner "Spree::Seeds::All.call; Spree::SampleData::Loader.call"`, execOpts);++ // 2. Extract credentials and write to temp file (shared with test files)+ const output = execSync(`${RAILS} runner '${CREDENTIALS_RUBY}'`, execOpts);+ const jsonMatch = output.match(/\{.*\}\s*$/);+ if (!jsonMatch) throw new Error(`Failed to parse credentials:\n${output}`);+ writeFileSync(CREDENTIALS_FILE, jsonMatch[0]);++ // 3. Boot Rails server+ serverProcess = spawn(+ 'bundle', ['exec', 'spec/dummy/bin/rails', 'server', '-p', PORT, '-e', 'test'],+ { cwd: API_GEM_DIR, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, RAILS_ENV: 'test', PORT } }+ );++ serverProcess.stderr?.on('data', (data: Buffer) => {+ const msg = data.toString();+ if (msg.includes('Error') || msg.includes('error')) console.error('[rails]', msg);+ });++ await waitForServer(`http://localhost:${PORT}/api/v3/store/products`);+}++export async function teardown() {+ if (serverProcess) {+ serverProcess.kill('SIGTERM');+ serverProcess = null;+ }+}diff --git a/packages/sdk/tests/integration/helpers.ts b/packages/sdk/tests/integration/helpers.tsnew file mode 100644index 0000000000..a85ddf7326--- /dev/null+++ b/packages/sdk/tests/integration/helpers.ts@@ -0,0 +1,64 @@+import { createClient } from '../../src';+import { getCredentials, type TestCredentials } from './setup';+import type { Client } from '../../src';++export function client() {+ const creds = getCredentials();+ return createClient({+ baseUrl: creds.base_url,+ publishableKey: creds.publishable_key,+ });+}++export function authOpts() {+ return { token: getCredentials().jwt_token };+}++export function testAddress(overrides: Record<string, string> = {}) {+ return {+ first_name: 'Test',+ last_name: 'Checkout',+ address1: '1 Times Square',+ city: 'New York',+ postal_code: '10036',+ country_iso: getCredentials().country_iso,+ state_abbr: 'NY',+ phone: '555-0100',+ ...overrides,+ };+}++/**+ * Build a cart through the checkout to a given step.+ */+export async function buildCart(throughStep: 'item' | 'address' | 'delivery' | 'payment') {+ const creds = getCredentials();+ const c = client();++ const products = await c.products.list();+ const variantId = products.data.find(p => p.purchasable && p.default_variant_id)!.default_variant_id;++ const cart = await c.carts.create();+ const opts = { spreeToken: cart.token };++ await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 1 }, opts);+ if (throughStep === 'item') return { c, cart, opts, creds };++ const withAddr = await c.carts.update(cart.id, {+ email: `test-${Date.now()}@example.com`,+ shipping_address: testAddress(),+ billing_address: testAddress(),+ }, opts);+ if (throughStep === 'address') return { c, cart: withAddr, opts, creds };++ const ful = withAddr.fulfillments[0];+ const withRate = await c.carts.fulfillments.update(cart.id, ful.id, {+ selected_delivery_rate_id: ful.delivery_rates[0].id,+ }, opts);+ if (throughStep === 'delivery') return { c, cart: withRate, opts, creds };++ const session = await c.carts.paymentSessions.create(cart.id, {+ payment_method_id: creds.bogus_payment_method_id,+ }, opts);+ return { c, cart: withRate, opts, creds, session };+}diff --git a/packages/sdk/tests/integration/markets.test.ts b/packages/sdk/tests/integration/markets.test.tsnew file mode 100644index 0000000000..0f6c3cd66a--- /dev/null+++ b/packages/sdk/tests/integration/markets.test.ts@@ -0,0 +1,37 @@+import { describe, it, expect } from 'vitest';+import { client } from './helpers';++describe('markets', () => {+ it('lists markets', async () => {+ const result = await client().markets.list();++ expect(result.data.length).toBeGreaterThan(0);+ const market = result.data[0];+ expect(market.id).toMatch(/^mkt_/);+ expect(market).toHaveProperty('name');+ expect(market).toHaveProperty('currency');+ });++ it('resolves market by country', async () => {+ const market = await client().markets.resolve('US');+ expect(market.id).toMatch(/^mkt_/);+ });+});++describe('countries', () => {+ it('lists countries', async () => {+ const result = await client().countries.list();++ expect(result.data.length).toBeGreaterThan(0);+ const country = result.data[0];+ expect(country).toHaveProperty('iso');+ expect(country).toHaveProperty('name');+ });++ it('gets a country with states', async () => {+ const country = await client().countries.get('US', { expand: ['states'] });++ expect(country.iso).toBe('US');+ expect(country.name).toBe('United States');+ });+});diff --git a/packages/sdk/tests/integration/setup.ts b/packages/sdk/tests/integration/setup.tsnew file mode 100644index 0000000000..3974e6195c--- /dev/null+++ b/packages/sdk/tests/integration/setup.ts@@ -0,0 +1,33 @@+/**+ * Per-file setup — reads credentials written by global-setup.ts.+ */+import { readFileSync } from 'fs';+import { resolve } from 'path';++export interface TestCredentials {+ base_url: string;+ publishable_key: string;+ jwt_token: string;+ user_email: string;+ user_password: string;+ product_slug: string;+ product_id: string;+ variant_id: string;+ category_id: string;+ category_permalink: string;+ country_iso: string;+ store_name: string;+ bogus_payment_method_id: string;+ check_payment_method_id: string;+}++const CREDENTIALS_FILE = resolve(__dirname, '.credentials.json');++let credentials: TestCredentials | null = null;++export function getCredentials(): TestCredentials {+ if (!credentials) {+ credentials = JSON.parse(readFileSync(CREDENTIALS_FILE, 'utf-8'));+ }+ return credentials!;+}diff --git a/packages/sdk/vitest.config.ts b/packages/sdk/vitest.config.tsindex 7e51e1a0ca..59b3b211cf 100644--- a/packages/sdk/vitest.config.ts+++ b/packages/sdk/vitest.config.ts@@ -10,6 +10,7 @@ export default defineConfig({test: {globals: true,environment: 'node',+ exclude: ['tests/integration/**', 'node_modules/**'],setupFiles: ['./tests/setup.ts'],coverage: {provider: 'v8',diff --git a/packages/sdk/vitest.integration.config.ts b/packages/sdk/vitest.integration.config.tsnew file mode 100644index 0000000000..e06a6acfdf--- /dev/null+++ b/packages/sdk/vitest.integration.config.ts@@ -0,0 +1,19 @@+import { defineConfig } from 'vitest/config';+import path from 'path';++export default defineConfig({+ resolve: {+ alias: {+ '@/types': path.resolve(__dirname, './src/types/generated/index.ts'),+ },+ },+ test: {+ globals: true,+ environment: 'node',+ include: ['tests/integration/**/*.test.ts'],+ globalSetup: ['./tests/integration/global-setup.ts'],+ testTimeout: 15_000,+ // Run sequentially — tests share server + SQLite database+ fileParallelism: false,+ },+});