Skip to content

Using the mock service with CORS

Beth Skurrie edited this page Jan 12, 2015 · 13 revisions

When you will be using CORS in real life and you want to verify the CORS requests

If your application will be making CORS requests in real life, and you want to verify the CORS and OPTIONS requests as part of your pact tests, then stub the OPTIONS request the way you would stub a normal request.

  some_provider
    .upon_receiving("a CORS request for /something")
    .with(method: 'options', path: '/something', headers: {
      'Access-Control-Request-Headers' => 'Content-Type',
      ....
    })
    .will_respond_with(
      status: 200,
      headers: {
        'Access-Control-Allow-Origin' => '....',
        'Access-Control-Allow-Headers' => 'Content-Type',
        'Access-Control-Allow-Methods' => 'PUT, POST....'
      }
    )

When you will not be using CORS in real life or you don't want to verify the OPTIONS requests

The mock service operates on a port that won't be the same as the port your tests are running on, which will generally cause your browser to make an OPTIONS request before it invokes the real request. If, in real life, you will be running your UI code and your back end on the same host and port, and will therefore not be using CORS, then you have two options for using the mock service.

Option 1. Turn off browser security in the tests

If you are using karma, use the following configuration (choose the browser(s) you want).

    browsers: ['PhantomJS_without_security','Chrome_without_security'],
    customLaunchers: {
      Chrome_without_security: {
        base: 'Chrome',
        flags: ['--disable-web-security']
      },
      PhantomJS_without_security: {
        base: 'PhantomJS',
        flags: ['--web-security=false']
      }
    }

Option 2. Start the mock service with the --cors-enabled option

Not released yet!

Start the mock service with --cors-enabled. This will allow the mock service to respond to OPTIONS requests for your mocked interactions, without you having to set up an OPTIONS interaction that would end up in the pact file.