The application of mocks and stubs in pattern testing
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:
- Unit Test Layer: Replace database access with stubs
sinon.stub(userRepository, 'findById').resolves({id: 1, name: 'Mock User'});
- 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:
- 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);
- 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:
- Share basic stub configurations
before(() => {
this.commonStub = sinon.stub(config, 'get').returns('test');
});
after(() => {
this.commonStub.restore();
});
- 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:
- 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);
- 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
上一篇:单元测试中的模式隔离技巧
下一篇:测试驱动开发(TDD)与设计模式