CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jasmine-jquery

jQuery matchers and fixture loader for Jasmine framework

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

json-fixtures.mddocs/

JSON Fixtures

JSON fixture management system for loading test data from external JSON files with automatic caching and data isolation. Perfect for testing components that process complex data structures without embedding large data objects in test files.

Capabilities

Global JSON Fixture Functions

loadJSONFixtures

Loads JSON fixture(s) from files and returns data object.

/**
 * Loads JSON fixture(s) from one or more files and returns data object
 * Data is keyed by filename for easy access
 * @param fixtureUrls - One or more JSON fixture file URLs/paths
 * @returns Object with fixture data keyed by filename
 */
function loadJSONFixtures(...fixtureUrls);

Usage Examples:

// Load single JSON fixture
var fixtures = loadJSONFixtures('users.json');
var users = fixtures['users.json'];

// Load multiple JSON fixtures
var data = loadJSONFixtures('users.json', 'products.json', 'orders.json');
var users = data['users.json'];
var products = data['products.json'];
var orders = data['orders.json'];

// Test with loaded data
expect(users).toHaveLength(3);
expect(products[0]).toHaveProperty('name');

getJSONFixture

Retrieves specific JSON fixture data by filename.

/**
 * Retrieves specific JSON fixture data by filename
 * Must be called after loadJSONFixtures() for the same file
 * @param fixtureUrl - JSON fixture file URL/path
 * @returns Parsed JSON data for the specified fixture
 */
function getJSONFixture(fixtureUrl);

Usage Example:

// Load fixtures first
loadJSONFixtures('users.json', 'config.json');

// Get specific fixture data
var users = getJSONFixture('users.json');
var config = getJSONFixture('config.json');

// Use in tests
expect(config.apiUrl).toBe('https://api.example.com');
expect(users[0].name).toBe('Alice');

JSON Fixture Management Class

Access JSON fixture management through jasmine.getJSONFixtures():

/**
 * JSON Fixture management singleton
 */
interface JSONFixtures {
  /** File path for JSON fixture files (default: 'spec/javascripts/fixtures/json') */
  fixturesPath: string;
  
  /** Internal cache object for loaded JSON fixtures */
  fixturesCache_: object;

  /** Load JSON fixtures from files and return data object */
  load(...fixtureUrls): object;
  
  /** Load JSON fixtures into cache and return cache object (same as load) */
  read(...fixtureUrls): object;
  
  /** Clear JSON fixture cache */
  clearCache(): void;
}

// Access the singleton
var jsonFixtures = jasmine.getJSONFixtures();

Configuration and Usage:

// Customize JSON fixture path
jasmine.getJSONFixtures().fixturesPath = 'test/fixtures/data';

// Use JSON fixture methods directly
var data = jasmine.getJSONFixtures().load('test-data.json');
jasmine.getJSONFixtures().clearCache();

JSON Loading Behavior

File Loading

  • JSON files loaded via synchronous AJAX requests
  • Files loaded relative to fixturesPath configuration
  • JSON content parsed automatically
  • Multiple files stored separately by filename key

Data Access Patterns

  • Data returned as object with filename keys
  • Each fixture file becomes a property in returned object
  • Use bracket notation to access: data['filename.json']
  • Use getJSONFixture() for direct single-file access

Caching and Data Isolation

  • All loaded JSON fixtures automatically cached by filename
  • Important: load() refetches data each time for isolation
  • Modifications to returned data don't affect cache
  • Cache persists across test runs unless manually cleared

Data Structure Examples

Example JSON Fixture Files

users.json:

[
  {
    "id": 1,
    "name": "Alice Johnson",
    "email": "alice@example.com",
    "active": true,
    "roles": ["user", "admin"]
  },
  {
    "id": 2, 
    "name": "Bob Smith",
    "email": "bob@example.com",
    "active": false,
    "roles": ["user"]
  }
]

config.json:

{
  "apiUrl": "https://api.example.com",
  "timeout": 5000,
  "features": {
    "authentication": true,
    "notifications": false
  },
  "supportedLanguages": ["en", "es", "fr"]
}

Using JSON Fixtures in Tests

Basic Data Loading:

describe('User management', function() {
  var users;
  
  beforeEach(function() {
    var fixtures = loadJSONFixtures('users.json');
    users = fixtures['users.json'];
  });

  it('should process user data', function() {
    expect(users).toHaveLength(2);
    expect(users[0].name).toBe('Alice Johnson');
    expect(users[0].roles).toContain('admin');
  });

  it('should filter active users', function() {
    var activeUsers = users.filter(user => user.active);
    expect(activeUsers).toHaveLength(1);
    expect(activeUsers[0].name).toBe('Alice Johnson');
  });
});

Configuration Testing:

describe('Application configuration', function() {
  var config;

  beforeEach(function() {
    config = getJSONFixture('config.json');
  });

  it('should have correct API configuration', function() {
    expect(config.apiUrl).toBe('https://api.example.com');
    expect(config.timeout).toBe(5000);
  });

  it('should have feature flags', function() {
    expect(config.features.authentication).toBe(true);
    expect(config.features.notifications).toBe(false);
  });
});

Data Isolation and Modification

Fresh Data Each Load

it('should provide fresh data each time', function() {
  // Load data first time
  var data1 = loadJSONFixtures('users.json');
  var users1 = data1['users.json'];
  
  // Modify the data
  users1[0].name = 'Modified Name';
  
  // Load data second time - should be fresh
  var data2 = loadJSONFixtures('users.json');
  var users2 = data2['users.json'];
  
  expect(users2[0].name).toBe('Alice Johnson'); // Original name, not modified
});

Safe Data Manipulation

describe('Data manipulation tests', function() {
  var testUsers;

  beforeEach(function() {
    // Get fresh copy for each test
    testUsers = getJSONFixture('users.json');
  });

  it('should modify user data safely', function() {
    // Safe to modify testUsers - won't affect other tests
    testUsers[0].active = false;
    testUsers.push({id: 3, name: 'Charlie', email: 'charlie@example.com'});
    
    expect(testUsers).toHaveLength(3);
    expect(testUsers[0].active).toBe(false);
  });

  it('should have original data in new test', function() {
    // testUsers is fresh copy, not affected by previous test
    expect(testUsers).toHaveLength(2);
    expect(testUsers[0].active).toBe(true);
  });
});

Advanced Usage Patterns

Complex Data Processing

describe('Data processing pipeline', function() {
  var rawData, processedData;

  beforeEach(function() {
    var fixtures = loadJSONFixtures('raw-data.json', 'lookup-tables.json');
    rawData = fixtures['raw-data.json'];
    var lookups = fixtures['lookup-tables.json'];
    
    // Process data using multiple fixtures
    processedData = rawData.map(item => ({
      ...item,
      categoryName: lookups.categories[item.categoryId],
      statusText: lookups.statuses[item.status]
    }));
  });

  it('should enrich data with lookup values', function() {
    expect(processedData[0]).toHaveProperty('categoryName');
    expect(processedData[0]).toHaveProperty('statusText');
  });
});

API Response Mocking

describe('API integration', function() {
  it('should handle user list response', function() {
    var mockResponse = getJSONFixture('api-responses/users-list.json');
    
    // Simulate API response processing
    var users = mockResponse.data;
    var pagination = mockResponse.pagination;
    
    expect(users).toHaveLength(mockResponse.pagination.perPage);
    expect(pagination.total).toBeGreaterThan(users.length);
  });

  it('should handle error responses', function() {
    var errorResponse = getJSONFixture('api-responses/error-401.json');
    
    expect(errorResponse.error.code).toBe(401);
    expect(errorResponse.error.message).toContain('Unauthorized');
  });
});

Error Handling

The JSON fixture system throws errors for:

/**
 * Specific error messages thrown by JSON fixture system:
 * - "JSONFixture could not be loaded: [url] (status: [status], message: [message])"
 * 
 * These errors occur when:
 * - JSON fixture file doesn't exist at specified path
 * - Network/file access issues during AJAX loading
 * - JSON parsing errors for malformed JSON files
 * - Invalid file paths or permission issues
 * - JSON files contain syntax errors or invalid JSON
 */

Error Handling Example:

try {
  var data = loadJSONFixtures('missing-file.json');
} catch (error) {
  expect(error.message).toContain('JSONFixture could not be loaded');
}

Configuration

Default Configuration

{
  fixturesPath: 'spec/javascripts/fixtures/json'  // Default JSON fixture directory (subdirectory of fixtures)
}

Custom Configuration

// Set custom JSON fixture path
jasmine.getJSONFixtures().fixturesPath = 'test/data/json';

// Verify configuration
expect(jasmine.getJSONFixtures().fixturesPath).toBe('test/data/json');

Best Practices

Organize JSON Fixtures by Purpose

spec/javascripts/fixtures/json/
├── users/
│   ├── admin-users.json
│   ├── regular-users.json
│   └── inactive-users.json
├── api-responses/
│   ├── success-responses.json
│   └── error-responses.json
└── config/
    ├── development.json
    └── production.json

Use Descriptive Fixture Names

// Good - descriptive names
loadJSONFixtures('users/admin-users.json', 'config/test-settings.json');

// Less clear
loadJSONFixtures('data1.json', 'settings.json');

Combine with Other Fixtures

describe('Complete component test', function() {
  beforeEach(function() {
    // Load HTML structure
    loadFixtures('user-table.html');
    
    // Load CSS styles
    loadStyleFixtures('table-styles.css');
    
    // Load test data
    var userData = getJSONFixture('users/sample-users.json');
    
    // Populate component with test data
    populateUserTable(userData);
  });

  it('should render users correctly', function() {
    expect($('.user-row')).toHaveLength(3);
    expect($('.user-name').first()).toHaveText('Alice Johnson');
  });
});

docs

css-fixtures.md

event-spying.md

html-fixtures.md

index.md

jquery-matchers.md

json-fixtures.md

tile.json