Let's say I have this API test and the URL and Credentials differ between production and development environments:
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
})
}
);
Now with Cypress tests you can have a json config file like this, one for each environment:
{
"env": {
"baseUrl": "example",
"standardUserEmail": "testing+standard@test.com",
"standardUserPassword": "test"
}
}
Then access it like so:
cy.request({
method: "POST",
url: `${Cypress.env("baseUrl")}/auth`,
})
How does one achieve something like this without using Cypress? A .env file doesn't solve this problem exactly and I also don't need one as I want the values stored in the repo.
Answer (TypeScript version):
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()
Then use like this:
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
})
}
);
