NodeJS TypeScript -如何根据环境访问常量?就像Cypress之外的Cypress.env()

rekjcdws  于 2023-03-22  发布在  Node.js
关注(0)|答案(2)|浏览(135)

假设我有这个API测试,并且生产和开发环境之间的URL和凭据不同:

before("Get auth token", async () => {
    await spec().post(`${baseUrl}/auth`)
      .withBody(
        {
          email: "testing+standard@test.com",
          password: "test"
        }
      )
      .expectStatus(200)
      .expect((ctx) => {
        expect(ctx.res.body.token).to.be.a("string")
        state.token = ctx.res.body.token
      })
    }
  );

现在使用Cypress测试,你可以有一个像这样的json配置文件,每个环境一个:

{
    "env": {
        "baseUrl": "example",
        "standardUserEmail": "testing+standard@test.com",
        "standardUserPassword": "test"
    }
}

然后像这样访问它:

cy.request({
      method: "POST",
      url: `${Cypress.env("baseUrl")}/auth`,
    })

如果不使用Cypress,如何实现这样的功能?. env文件并不能完全解决这个问题,我也不需要它,因为我希望将值存储在repo中。

    • 答案(TypeScript版本)**:
interface Environment {
    baseUrl: string;
    standardUserEmail: string;
    standardUserPassword: string
} 

type Environments = {
    development: Environment
    production: Environment
}

// Define environments with the relevant data as a map
const environments: Environments = {
    development:  {
        baseUrl: 'https://example.com',
        standardUserEmail: 'testing+standard@example.com',
        standardUserPassword: 'example',
    },
    production: {
        baseUrl: '',
        standardUserEmail: '',
        standardUserPassword: '',
    },
}

// Get the environment name from the command line
// or default to development
const getEnvironmentData = (): Environment => {
    const environment = process.env.ENVIRONMENT || 'development';
    console.log(`Using environment: ${environment}`);
    // Get the environment data from the map
    return environments[environment as keyof Environments]
};

// Export the environment data
export = getEnvironmentData()

然后像这样使用:

import 'mocha';
import { spec, request } from "pactum";
import { expect } from "chai"
import config from "../../config"

describe('Example Test API', function () {
  const state = {
    token: "",
  };

  before("Get auth token", async () => {
     request.setBaseUrl(config.baseUrl)
     await spec().post('/auth')
      .withBody(
        {
          email: config.standardUserEmail,
          password: config.standardUserPassword
        }
      )
      .expectStatus(200)
      .expect((ctx) => {
        expect(ctx.res.body.token).to.be.a("string")
        state.token = ctx.res.body.token
      })
    }
  );
envsm3lx

envsm3lx1#

在你的第一个例子中,看起来你正在使用PactumJS。如果你想支持多个环境,并且能够轻松地在它们之间进行选择,你可以使用环境变量和环境Map的组合,类似于Cypress中定义的方式。

// define your environments with the relevant data as a map
const environments = {
    development: {
        baseUrl: 'http://httpbin.org',
        standardUserEmail: 'dev+test@email.com',
        standardUserPassword: 'dev-test-password',
    },
    staging: {
        baseUrl: 'https://staging.example.com',
        standardUserEmail: 'stg+test@email.com',
        standardUserPassword: 'stg-test-password',
    },
    production: {
        baseUrl: 'https://example.com',
        standardUserEmail: 'prod+test@email.com',
        standardUserPassword: 'prod-test-password',
    },
}

// get the environment name from the command line
// or default to development
const getEnvironmentData = () => {
    const environment = process.env.ENVIRONMENT || 'development';
    console.log('Using environment: ', environment);
    // get the environment data from the map
    const environmentData = environments[environment];
    return environmentData;
};

// export the environment data
module.exports = {
    environmentData: getEnvironmentData(),
};

使用所有相关数据定义了Map之后,就可以轻松地在测试中引用它们。

const { spec, request } = require('pactum');
const { environmentData } = require('../config');

before(() => {
    request.setBaseUrl(environmentData.baseUrl);
    console.log(environmentData.standardUserEmail);
    console.log(environmentData.standardUserPassword);
});

it('should get a response with status code 200', async () => {
    await spec()
        .get('/status/200')
        .expectStatus(200);
});

最后,您可以通过使用环境变量轻松地在环境数据之间切换。
您将使用process.env.ENVIRONMENT访问变量,该变量将Map回您在测试命令之前指定的变量。请参见下图:

对于一个工作示例:请看我在GitHub上创建的示例项目:https://github.com/dimitriharding/pactumjs-with-dynamic-environtments

wj8zmpe1

wj8zmpe12#

我认为您的需求可以通过使用dotenv来实现。

相关问题