Search code examples
ember.jsember-cliember-cli-mirage

Ember mirage server is not defined in tests


I am trying to integrate ember-cli-mirage fixtures into some tests. I followed the documentation here: ember fixtures

Problem: The server is not defined. error message: ReferenceError: server is not defined

model-test.js:

import { moduleForModel, test } from 'ember-qunit';

moduleForModel('network', 'Unit | Model | network', {
  needs: []
});

test('it exists', function(assert) {
  server.loadFixtures('networks'); //no defined

andThen(function() {
   let net1 = networks.first();
});
  assert.ok(true);
});

I have also verified that the config is set to true.

ENV['ember-cli-mirage'] = {
        enabled: true
    }

Solution

  • Mirage starts up in an initializer. Since initializers only run when a full Ember app boots up, by default the Mirage server is only available in an acceptance test.

    To use Mirage in an integration or unit test, follow the docs on manually starting your Mirage server. Currently the docs say this:

    To run your Mirage server during a unit or integration test, first create a helper:

    // tests/helpers/start-mirage.js
    import mirageInitializer from '../../initializers/ember-cli-mirage';
    
    export default function startMirage(container) {
       mirageInitializer.initialize(container);
     }
    

    Then, add the following to any test where you want Mirage to initialize:

    // tests/integration/components/your-test.js
     import startMirage from '../../../helpers/start-mirage';
    
    moduleForComponent('your-component', 'Integration | Component | your component', {
       integration: true,
       setup: function() {
         startMirage(this.container);
       }
     });