阿里云主机折上折
  • 微信号
Current Site:Index > The application of mocks and stubs in pattern testing

The application of mocks and stubs in pattern testing

Author:Chuan Chen 阅读数:46383人阅读 分类: JavaScript

Basic Concepts of Mock and Stub

Mocks and stubs are specific implementations of test doubles used to isolate the code under test from external dependencies. Mock objects verify interaction behaviors, while stub objects provide predefined responses. In JavaScript testing, both are often implemented using libraries like Sinon.js.

// Stub example
const stub = sinon.stub().returns(42);
console.log(stub()); // Output: 42

// Mock example
const mock = sinon.mock(api);
mock.expects('fetchData').once().returns(Promise.resolve({data: 'test'}));

Differences Between Behavior Verification and State Verification

Mocks focus on behavior verification, checking whether methods are called as expected. Stubs emphasize state verification, ensuring the code produces correct outputs for specific inputs. Jest's jest.fn() combines both features:

// Behavior verification
const mockFn = jest.fn();
[1, 2].forEach(mockFn);
expect(mockFn).toHaveBeenCalledTimes(2);

// State verification
const stubFn = jest.fn(x => x * 2);
expect(stubFn(3)).toBe(6);

Practical Applications in the Testing Pyramid

These techniques should be used differently across the layers of the testing pyramid. Stubs are more common in unit tests, while mocks are used more in integration tests:

  1. Unit Test Layer: Replace database access with stubs
sinon.stub(userRepository, 'findById').resolves({id: 1, name: 'Mock User'});
  1. Integration Test Layer: Verify API call sequences
const mock = sinon.mock(paymentService);
mock.expects('charge').withExactArgs(100, 'USD').once();

Special Handling for Asynchronous Scenarios

Special attention is needed for handling Promises and async/await. Sinon provides resolves and rejects methods:

// Asynchronous stub
const asyncStub = sinon.stub()
  .onFirstCall().resolves('first')
  .onSecondCall().rejects(new Error('failed'));

// Asynchronous mock
const mockAPI = sinon.mock(fetch);
mockAPI.expects('get').withArgs('/users').returns(
  Promise.resolve({status: 200, json: () => ({data: []})})
);

Test Framework Integration Examples

Typical integration methods in mainstream testing frameworks:

Jest Solution:

// Automatically mock an entire module
jest.mock('../api', () => ({
  fetchData: jest.fn().mockResolvedValue({data: []})
}));

// Manual cleanup
afterEach(() => {
  jest.clearAllMocks();
});

Mocha+Sinon Solution:

describe('UserService', () => {
  let sandbox;
  
  beforeEach(() => {
    sandbox = sinon.createSandbox();
  });
  
  afterEach(() => {
    sandbox.restore();
  });
  
  it('should call API', () => {
    const stub = sandbox.stub(axios, 'get').resolves({data: {}});
    // Test logic
  });
});

Boundary Conditions and Error Handling

Mocks and stubs are particularly important in exception testing, as they can force error states that are difficult to trigger in normal flows:

// Simulate network errors
sinon.stub(axios, 'post').rejects({
  response: {
    status: 500,
    data: { error: 'Internal Server Error' }
  }
});

// Verify error handling
const consoleStub = sinon.stub(console, 'error');
await someFunctionThatShouldHandleErrors();
expect(consoleStub).toHaveBeenCalledWith('Error occurred');

Anti-Patterns of Overuse

Overusing test doubles can lead to excessive coupling between tests and implementations. Common issues include:

  1. Verifying internal implementation details instead of external behaviors
// Wrong approach: Testing implementation details like call counts
expect(mockFn).toHaveBeenCalledTimes(3);

// Correct approach: Verifying the final state
expect(result).toEqual(expectedValue);
  1. Creating deeply nested stub objects
// Example of over-stubbing
sinon.stub(db, 'query').returns({
  then: sinon.stub().returns({
    catch: sinon.stub().returns({
      finally: sinon.stub()
    })
  })
});

Collaboration with Dependency Injection

Dependency injection allows more flexible use of test doubles:

class OrderProcessor {
  constructor(paymentService = new RealPaymentService()) {
    this.paymentService = paymentService;
  }
  
  process(order) {
    return this.paymentService.charge(order.total);
  }
}

// Inject stubs during testing
const stubService = { charge: sinon.stub().resolves(true) };
const processor = new OrderProcessor(stubService);

Differences Between Browser and Node Environments

Special considerations for different runtime environments:

Browser Environment:

// Mock XMLHttpRequest
const xhr = sinon.useFakeXMLHttpRequest();
xhr.onCreate = (request) => {
  request.respond(200, {}, '{"data": "test"}');
};

// Restore original implementation
xhr.restore();

Node Environment:

// Intercept HTTP requests
nock('https://api.example.com')
  .get('/users')
  .reply(200, {users: [{id: 1}]});

Performance Optimization Techniques

Optimization strategies for large-scale test suites:

  1. Share basic stub configurations
before(() => {
  this.commonStub = sinon.stub(config, 'get').returns('test');
});

after(() => {
  this.commonStub.restore();
});
  1. Use factory functions to generate test doubles
function createUserStub(overrides = {}) {
  return {
    id: 1,
    name: 'Test User',
    ...overrides
  };
}

Version Compatibility Issues

Behavioral differences between versions of testing libraries:

  1. Breaking changes between Sinon 2.x and 5.x
// Old version
sinon.stub(obj, 'method').returns(42);

// New version requires replace
sinon.replace(obj, 'method', () => 42);
  1. Evolution of Jest's auto-mocking system
// Legacy manual mocking
jest.mock('module', () => 'mock');

// New version supports auto-mocking
jest.unstable_mockModule('module', {...});

Visual Test Debugging Tools

Use visualization tools to debug complex interactions:

// Use sinon-chrome to mock extension APIs
const chrome = require('sinon-chrome');
global.chrome = chrome;

chrome.runtime.sendMessage.yields({response: 'ok'});

// View call records after testing
console.log(chrome.runtime.sendMessage.getCalls());

Type Integration with TypeScript

Type-safe ways to create test doubles:

interface UserService {
  getUser(id: number): Promise<User>;
}

// Typed stub
const stubService = sinon.createStubInstance<UserService>(UserServiceImpl);
stubService.getUser.resolves({id: 1, name: 'Typed User'});

// Type-safe mock
const mock = sinon.mock<UserService>(realService);
mock.expects('getUser').withArgs(1);

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.