Skip to content

Using the mock service with CORS

Beth Skurrie edited this page Jun 29, 2017 · 13 revisions

If you are using the Pact to run Javascript tests within a browser, you will have to deal with CORS because the port that the mock service is running on will not be the same as the port your tests are running from. You can handle this in a few ways, depending on whether or not you will be using CORS in real life, and whether or not you want to use Pact to verify the CORS requests.

When you will be using CORS in real life, and you want Pact 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 Pact to verify CORS requests

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 option

Start the mock service with --cors. 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.