You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jest模拟被依赖模块函数?(Cassandra驱动测试场景)

Testing createCassandraDriver with Jest: Mocking Dependencies

Alright, let's walk through how to test your createCassandraDriver function with Jest by mocking the cassandra-driver dependency. We'll cover both successful client creation and error handling scenarios, plus address edge cases like the authProvider function in your code.

1. Mock the Entire cassandra-driver Module

First, we need to mock cassandra-driver to avoid spinning up real Cassandra connections during tests. Jest's jest.mock lets us replace the module with a mock implementation where we can track calls to the Client constructor and mock consistency types.

Add this at the top of your test file:

jest.mock('cassandra-driver', () => {
  // Mock the Client class to track instantiation
  const MockClient = jest.fn();
  
  // Mock consistency types to match what your code uses
  const MockTypes = {
    consistencies: {
      quorum: 'quorum' // Use the same value as the real driver, or any placeholder
    }
  };

  // Include this if your authProvider uses driver-specific auth classes (like PlainTextAuthProvider)
  const MockPlainTextAuthProvider = jest.fn();

  return {
    Client: MockClient,
    types: MockTypes,
    auth: { PlainTextAuthProvider: MockPlainTextAuthProvider }
  };
});

2. Test Successful Client Creation

Next, let's verify that when valid config is passed, the function correctly creates a Client instance with the right parameters and resolves it.

Import your function and the mocked driver, then write the test:

const createCassandraDriver = require('./path-to-your-module'); // Update this path
const driver = require('cassandra-driver');

describe('createCassandraDriver', () => {
  // Reset mocks before each test to avoid cross-test contamination
  beforeEach(() => {
    driver.Client.mockClear();
    if (driver.auth?.PlainTextAuthProvider) {
      driver.auth.PlainTextAuthProvider.mockClear();
    }
  });

  it('resolves a Client instance with correct configuration', async () => {
    // Define test config values
    const testConfig = {
      cassandra_user: 'test-user',
      cassandra_password: 'test-pass',
      cassandra_address: '127.0.0.1:9042,127.0.0.2:9042'
    };

    // Call the function under test
    const result = await createCassandraDriver(testConfig);

    // Verify the Client constructor was called exactly once
    expect(driver.Client).toHaveBeenCalledTimes(1);

    // Verify the Client was initialized with the right parameters
    const expectedContactPoints = testConfig.cassandra_address.split(',');
    const expectedAuthProvider = driver.auth.PlainTextAuthProvider.mock.results[0].value; // For driver auth classes
    // OR if authProvider is your custom function:
    // const expectedAuthProvider = authProvider(testConfig.cassandra_user, testConfig.cassandra_password);

    expect(driver.Client).toHaveBeenCalledWith({
      contactPoints: expectedContactPoints,
      authProvider: expectedAuthProvider,
      queryconfig: { consistency: driver.types.consistencies.quorum }
    });

    // Verify the resolved value is a Client instance
    expect(result).toBeInstanceOf(driver.Client);
  });
});

3. Test Error Handling

We also need to ensure that if creating the Client throws an error, the function rejects with that error. Here's how to test that:

it('rejects with the error if Client creation fails', async () => {
  // Create a test error to throw
  const testError = new Error('Failed to initialize Cassandra client');
  
  // Make the Client constructor throw our test error
  driver.Client.mockImplementation(() => {
    throw testError;
  });

  const testConfig = {
    cassandra_user: 'test-user',
    cassandra_password: 'test-pass',
    cassandra_address: '127.0.0.1:9042'
  };

  // Verify the function rejects with the correct error
  await expect(createCassandraDriver(testConfig)).rejects.toThrow(testError);
});

Note on Your authProvider Function

If authProvider is a custom function in your module, you might want to mock it too to isolate the test. For example, if it's exported from the same file:

const { authProvider } = require('./path-to-your-module');
jest.spyOn(require('./path-to-your-module'), 'authProvider').mockReturnValue('mock-auth-token');

This lets you verify it's called with the right user/password without testing its internal logic here.

内容的提问来源于stack exchange,提问作者David Faizulaev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:51:14