Mock services using server.js and proxy.config.jso

2020-05-02 17:31发布

问题:

I am trying to mock service using server.js and the proxy.config.json file so I can use that mocked service in a Protractor test. The way I'm going about it is having the test file like this:

const server = require('server');
const { get, post } = server.router;
const { json } = server.reply;

server({ port: 3000 }, [
    get('/abc', ctx => { 
        return json({
            foo: "bar"
        })
    })
]);

and the proxy.config.json file like this:

{
    "/xyz": {
        "target": "http://localhost:3000/abc",
        "changeOrigin": true,
        "secure": false,
        "logLevel": "debug",
        "pathRewrite": {
            "^/xyz": ""
        }
    }
}

Then I run my tests by calling

ng e2e --proxy-config proxy.config.json

However, I am not being successful because my application runs, for example, in http://localhost:49156 and the service I wish to mock runs in https://localhost:8443/xyz. If I wish to mock and proxy something coming from the same port/protocol as the application (49156 and HTTP) I am able to do so, however, for the service running in port 8443 and https I am not able to. Can someone help me with this? What am I doing wrong? Thank you for your time.

回答1:

I was finally able to solve my initial issue by creating an environmentE2E.ts file as such:

export const environment = {
  production: false,
  baseURL: 'http://localhost:49156'
};

adding the following in angular-cli.json file:

      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts",
        "e2e": "environments/environmentE2E.ts"  // Added only this line, the others were already there
      }

and called the tests with the following command:

ng e2e --proxy-config proxy.config.json --environment e2e

Hope it helps others. Thank you.