DevelopersTesting

Testing

Test Overview

LayerFrameworkTestsCommand
Contract unit testsScarb (inline #[cfg(test)])22bash scripts/test-unit.sh
Contract integrationsnforge88cd packages/contracts && snforge test
BackendVitestpnpm --filter @moonight/backend test
Frontendpnpm --filter @moonight/frontend build (type check)

Contract Unit Tests

Inline tests in Cairo source files. These test pure math functions and don’t require snforge:

bash scripts/test-unit.sh

This runs a minimal Scarb build with only the math modules (no OpenZeppelin dependencies), keeping memory usage low.

Tests included:

  • fixed_point.cairo — 13 tests (mul_fp, div_fp, from_bps, to_bps, normalize_price)
  • interest.cairo — 9 tests (interest accrual over various time periods)

Contract Integration Tests

Full integration tests using Starknet Foundry. These require 16GB+ RAM.

cd packages/contracts
 
# Enable snforge_std (commented out by default for low-memory builds)
sed -i 's/# snforge_std/snforge_std/' Scarb.toml
 
# Run tests
snforge test

Test Files

FileTestsCoverage
test_fixed_point.cairo37All fixed-point math operations
test_moonusd.cairo10Minting, burning, roles, pause
test_position_nft.cairo8Mint, burn, ownership, supply
test_cdp_lifecycle.cairo10Open, deposit, withdraw, repay, close
test_stability_pool.cairo6Deposit, withdraw, absorb, compounding
test_oracle.cairo6Price fetch, staleness, emergency
test_vault_c.cairo11ERC-4626 deposit, withdraw, redeem, compound

Writing a New Test

Tests go in packages/contracts/tests/. Use the test utilities:

use moonight::test_utils::setup::{deploy_moonusd, deploy_mock_oracle};
use snforge_std::{declare, ContractClassTrait, start_cheat_caller_address};
 
#[test]
fn test_my_feature() {
    let owner = starknet::contract_address_const::<'owner'>();
    let moonusd_addr = deploy_moonusd(owner);
 
    // Use start_cheat_caller_address to impersonate callers
    start_cheat_caller_address(moonusd_addr, owner);
 
    // ... test logic
 
    // Assert expected results
    assert(result == expected, 'Unexpected result');
}

Test Utilities

Located in packages/contracts/src/test_utils/:

ModuleFunctions
setup.cairodeploy_moonusd(), deploy_position_nft(), deploy_mock_erc20(), deploy_mock_oracle(), deploy_full_protocol()
mock_erc20.cairoMinimal ERC-20 for testing (mint, transfer, approve)
mock_oracle.cairoConfigurable price oracle for testing
mock_extended.cairoMock Extended DEX for Vault A tests

Backend Tests

pnpm --filter @moonight/backend test        # run once
pnpm --filter @moonight/backend test:watch  # watch mode

CI Pipeline

All tests run automatically on push and pull requests:

JobWhat it tests
contracts-buildscarb build compiles all contracts
contracts-test-unitInline #[cfg(test)] math tests
contracts-test-integrationsnforge integration tests
frontend-buildNext.js build (type checking)
frontend-lintESLint
backend-buildTypeScript compilation