Testing with Mirage and Mocha

I’m building out an app in Ember 2.2 and it’s going pretty well in development but I’m hitting a few snags when testing. First, the app/mirage/config.js that I’m using:

export default function() {

  this.get('/tasks', function(db) {
    return {
      data: db.tasks.map((attrs) => (
        {
          type: 'tasks',
          id: attrs.id,
          attributes: attrs
        }
      ))
    };
  });

  this.get('/tasks/:id', function(db, request) {
    let task = db.tasks.find(request.params.id);
    return {
      data: {
        type: 'tasks',
        id: task.id,
        attributes: task
      }
    };
  });
...

The following route will return all of the tasks that I’ve told it to in app/mirage/config.js:

`import Ember from 'ember'`

TasksIndexRoute = Ember.Route.extend(
  {
    model: ->
      @store.findAll('task')
  }
)

`export default TasksIndexRoute`

But, the default route test doesn’t seem to know anything about mirage. I’ve gotten this far in tests/unit/routes/tasks/index-test.coffee:

`import { expect } from 'chai'`
`import { describeModule, it } from 'ember-mocha'`
`import { before } from 'mocha'`
`import Server from 'ember-cli-mirage/server'`
`import TaskFactory from 'automation/mirage/factories/task'`

describeModule(
  'route:tasks/index',
  'TasksIndexRoute',
  {
    # Specify the other units that are required for this test.
    needs: ['model:task']
  },
  ->
    it 'exists', ->
      route = @subject()
      expect(route).to.be.ok

    describe 'model', ->
      before ->
        server = new Server({environment: 'test'})
        server.loadFactories({task: TaskFactory})
        server.createList('task', 10)

      it 'finds all of the tasks', ->
        expect(@subject().model().get('length')).to.eq(10)
)

But, now Mirage is telling me I haven’t configures the ‘/tasks’ route (which I have and does work in development):

Mirage: Your Ember app tried to GET '/tasks', but there was no route defined to handle this request. Define a route that matches this path in your mirage/config.js file. Did you forget to add your namespace?console.(anonymous function) @ testem.js:721

I did manage to get an acceptance test working (I think) but I’d prefer to have unit tests as well as it’s easier to examine what the model hook is returning rather than just scraping the page for elements.

Thanks!

There’s a bit more involved in instantiating a Mirage server, so I’d suggest following the cookbook entry for running the initializer manually:

http://www.ember-cli-mirage.com/docs/v0.1.x/manually-starting-mirage/

1 Like

Nice. Thanks for the link.