Ember CLI

MIRAGE

Q: So what is it?

A: A way to help you mock out an API for testing purposes.

Q: But I already use Pretender...

A: Pretender focuses on mocking out endpoints, this focuses on loading the database of a fake server.

Q: Does it do anything else cool?

A: It has factory and fixture generation built in so you won't need to include a separate library for that.

Q: Anything else?

A: In addition to running during testing, this fake server can also run during development!

Q: So how do I get started?

A: learn to do four things:

  1. define API routes
  2. define factories
  3. use in tests
  4. use in development

Getting started...

1. Define your API routes

// app/mirage/config.js

export default function() {
  this.get('/users');
  this.post('/users');

  // These are shorthand for:
  // this.get('/users', function(db, request) {
  //   return {
  //     users: db.users
  //   };
  // });
  // this.post('/users', function(db, request) {
  //   var attrs = JSON.parse(request.requestBody);
  //   var user = db.users.insert(attrs);
  //   return user;
  // });
}

Getting started...

2. Define your factories

Note: we're gonna focus on doing things the factory way (instead of the fixture way)

// app/mirage/factories/user.js

import Mirage, { faker } from 'ember-cli-mirage';

export default Mirage.Factory.extend({
  name(i) { return `Person ${i}`; },
  age: 28,
  admin: false,
  avatar: faker.internet.avatar
});

Getting started...

3. Writing a test

// tests/acceptance/users-test.js

test("I can view the users", function() {
  var users = server.createList('user', 3);

  visit('/users');

  andThen(function() {
    equal( find('li').length, 3 );
    equal( find('li:first').text(), users[0].name );
  });
});

Getting started...

4. Using in development

// app/mirage/scenarios/default.js

export default function(server) {
  server.createList('post', 10);

  var user = server.create('user', {name: 'Zelda'});
  server.createList('comment', 20, {user_id: user.id});
}

Questions?

Thanks!

Made with Slides.com