Creating a Mock Data Service

One of the benefits of decoupling the view from a specific data access strategy is that you can easily change the way you access data without changing anything else in your application. For example, you could use a mock data service for quick prototyping or for unit testing, and a REST-based service for production. In this unit, we create a mock data service that implements the exact same API as the REST-based data service we created in the previous unit.

Steps

  1. In the /js directory, create a new file named employee-service-mock.js

  2. In employee-service-mock.js, define an array holding your mock data.

    let employees = [
      {
        id: 1,
        firstName: "Amy",
        lastName: "Taylor",
        phone: "617-564-3254",
        picture: "https://s3-us-west-1.amazonaws.com/sfdc-demo/people/amy_taylor.jpg"
      },
      {
        id: 2,
        firstName: "Anup",
        lastName: "Gupta",
        phone: "617-564-1258",
        picture: "https://s3-us-west-1.amazonaws.com/sfdc-demo/people/anup_gupta.jpg"
      }
    ];
    
  3. Create function named findAll defined as follows:

    export let findAll = () => new Promise(resolve => resolve(employees));
    

    Highlights:

    • The function has the same signature as the findAll() function defined in employee-service.js
    • The function returns the in-memory array as opposed to making a REST call for data
  4. In app.js, change the import statement to import employee-service-mock instead of employee-service

  5. Build the app:

     npm run webpack
    
  6. Make sure your local http server is started, open a browser and access http://localhost:8080.

Solution

The final code for this step is available in this branch.

comments powered by Disqus