The Mock.mock() method is used to either generate random data based on a template or to intercept specific URL requests. It supports several different invocation patterns:
- Generate data from a template:
Mock.mock(template) returns the generated data immediately. - Intercept a URL with a template:
Mock.mock(rurl, template) intercepts requests to rurl and returns data matching the template. - Intercept a URL with a specific response type:
Mock.mock(rurl, rtype, template) allows specifying the response type (e.g., status code or content type) along with the template. - Use a function for dynamic data: Instead of a template, you can pass a function as the second or third argument to generate data dynamically based on request options.
When intercepting URLs, Mock.mock() returns the Mock instance, allowing for method chaining.
// 1. Generate data from a template
var data = Mock.mock({ 'id': '@integer(1, 100)' });
// 2. Intercept XHR requests
Mock.mock('/api/user', { 'name': 'John Doe' });
// 3. Intercept with response type and template
Mock.mock('/api/data', 'json', { 'list': '@array(10, 1)' });
// 4. Use a function for dynamic responses
Mock.mock('/api/dynamic', function(options) {
return { 'status': 'success', 'data': options.body };
});