A minimal, shareable Cypress project for testing email workflows with Gmail through the Google API. This project is a compgnon to the article available at : https://www.clever-age.com/tester-les-emails-un-enjeu-cle-pour-la-qualite-logicielle/
This project demonstrates how to:
- Authenticate with Google OAuth2
- Access Gmail via the Google API
- Write Cypress tests that verify email content
Perfect for:
- Testing email notifications in your workflow
- Automating email-based test scenarios
- Learning Cypress + Google API integration
- Node.js v16 or higher (download)
- npm or yarn package manager
- A Google Cloud Project with Gmail API enabled
- A Gmail account for testing
-
Clone the repository:
git clone https://github.com/YOUR_USERNAME/cypress-gmail-api-testing.git cd cypress-gmail-api-testing -
Install dependencies:
npm install
-
Set up Google OAuth credentials (see section below)
- Go to Google Cloud Console
- Create a new project (name it
cypress-gmail-testing) - Enable the Gmail API:
- Go to APIs & Services β Library
- Search for "Gmail API"
- Click Enable
- Go to APIs & Services β Credentials
- Click Create Credentials β OAuth 2.0 Client ID
- Select Application Type: Desktop app
- Download the JSON credentials file
- Rename to
credentials.jsonand place in the project root
Your credentials.json structure should look like:
{
"installed": {
"client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
"client_secret": "YOUR_CLIENT_SECRET",
"redirect_uris": ["http://localhost"],
...
}
}Run the authentication script:
npx ts-node auth.tsThis will:
- Generate an authorization URL
- Open it in your browser
- Connect to the Gmail account and approve access to Gmail
- Copy the code in the url attribute ?code=XXXX
- Paste the code to the terminal
- It will generate a
token.jsonfile (contains your refresh token) in the project root
Your token.json structure sould look like this:
{
"access_token": "XXX",
"refresh_token": "XXX",
"scope": "https://www.googleapis.com/auth/gmail.readonly",
"token_type": "Bearer",
"expiry_date": 1767709000000
}
credentials.json or token.json to GitHub!
(They're in .gitignore by default)
cypress-gmail-api-testing/
βββ src/
β βββ auth.ts # OAuth2 authentication script
β βββ utils.ts # Helper functions for Gmail operations
βββ cypress/
β βββ e2e/
β β βββ gmail.spec.ts # Example Gmail tests
β βββ support/
β βββ e2e.ts # Cypress support configuration
β βββ commands.ts # Custom Cypress commands
βββ config/
β βββ credentials.example.json # OAuth credentials template (shown for reference)
βββ cypress.config.ts # Cypress configuration with Gmail task
βββ tsconfig.json # TypeScript configuration
βββ package.json # Project dependencies
βββ .gitignore # Files to exclude from Git
βββ .env.example # Environment variables template
βββ README.md # This file
βββ LICENSE # MIT License
Use the getLastEmail task in one of your tests.
The project includes a sample test in cypress/e2e/gmail.spec.ts:
describe('Lecture Gmail', () => {
it('Récupère le dernier email', () => {
cy.task('getLastEmail').then((snippet) => {
cy.log('Dernier mail :', snippet);
expect(snippet).to.include(''); // Verify expected content
});
});
});What it does:
- Calls the
getLastEmailcustom task (defined incypress.config.ts) - Fetches the most recent email from your Gmail inbox
- Logs the email snippet
- Verifies the content exists
- Gmail Task: The
getLastEmailtask authenticates with Gmail and fetches the latest email snippet - Custom Tasks: Add more tasks via
on('task', { ... }) - Base URL: Modify as needed for your application
initializeOAuth2Client()- Create OAuth2 clientsetOAuth2Credentials()- Set credentials for clientloadCredentials()- Load credentials from fileloadTokens()- Load tokens from file
Example usage in tests:
import { loadCredentials, loadTokens } from '../src/utils';
const credentials = loadCredentials('credentials.json');
const tokens = loadTokens('token.json');β Do:
- Keep
credentials.jsonandtoken.jsonin.gitignore - Use environment variables for sensitive data in CI/CD
- Rotate OAuth tokens regularly
- Restrict Gmail API scopes to what you need
β Don't:
- Commit credentials or tokens to GitHub
- Share your
credentials.jsonfile - Use your personal Google account in CI/CD (create a service account)
- Log sensitive data in test results
Define reusable commands in cypress/support/commands.ts:
Cypress.Commands.add('checkLastEmail', (expectedText) => {
cy.task('getLastEmail').then((snippet) => {
expect(snippet).to.include(expectedText);
});
});Solution: Ensure credentials.json is in the project root directory (not in the ressource/ folder)
Solution: Your token has expired. Delete token.json and run npx ts-node auth.ts again
Solution:
- Go to Google Cloud Console
- Select your project
- Go to APIs & Services β Library
- Search for "Gmail API" and click Enable
Solution: Increase Cypress timeout in cypress.config.ts:
export default defineConfig({
e2e: {
requestTimeout: 10000,
taskTimeout: 10000,
},
});This project is licensed under the MIT License β see LICENSE file for details.
Contributions are welcome! Please feel free to:
- Fork the repository
- Create a feature branch
- Submit a pull request
For issues or questions:
- Check the Cypress Documentation
- Review the Google Gmail API Docs
- Open an issue on GitHub
Happy Testing! π