How to configure Cypress for e2e in Github Actions? - vue.js

I am trying to do an e2e test on my VueJS app that uses axios for API calls. In my vue component, in the mounted, i do an API call. My idea would be to mock this call with cy.intercept and cy.wait, however i can't make it work. On my local environment when i launch my frontend and backend servers, my test passes as the API call is made. However, the call is not silenced and the cy.wait('#apiCall') does not work.
Also my test does not work in Github Actions, i have this error : AxiosError: The following error originated from your application code, not from Cypress. It was caused by an unhandled promise rejection.. I have the impression that github actions need a special ci environment file but i don't know where to tell cypress to look into those env variables when in continous integration.
Anyone had the same issue or knows about cypress X axios X github actions combined ?
Some of my code :
test.cy.js
cy.intercept('GET', '/coaches/coach-informations/30283', {
data: {
email: 'hello#hello.com',
},
}).as('getCoach')
cy.visit('/hello?coach=30283')
cy.wait('#getCoach')
component.vue
async mounted() {
await axios.get(`/coaches/coach-informations/30283/`)
}
.env
API_URL=http://127.0.0.1:8000/api
test-frontend.yml
name: GitHub Actions Demo
on: [pull_request, push]
jobs:
cypress-run:
runs-on: ubuntu-latest
env:
working-directory: front
steps:
- name: Checkout
uses: actions/checkout#v3
- name: Install node
uses: actions/setup-node#v3
with:
node:version: 'node-version'
- name: Get yarn cache directory path 🛠
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
working-directory: ${{env.working-directory}}
- name: Cache node_modules 📦
uses: actions/cache#v2.1.7
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: yarn-${{ hashFiles('front/yarn.lock') }}
restore-keys: |
yarn-
- name: Install dependencies 👨🏻‍💻
working-directory: ${{env.working-directory}}
run: yarn
- name: Cypress run
uses: cypress-io/github-action#v2
with:
working-directory: ${{env.working-directory}}
build: yarn build
start: yarn vite
wait-on: 'http://localhost:3000'
wait-on-timeout: 120
config-file: cypress.config.js
record: true
env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

I would say the URL used in the intercept is not catching the request from the app.
Locally you have a server running, so axios is ok but on Github the server is absent and the axios call fails.
It looks like you just need to add wildcard characters before the URL fragment
cy.intercept('GET', '**/coaches/coach-informations/30283', {
data: {
email: 'hello#hello.com',
},
}).as('getCoach')

Related

How to get env variables from env in github action .yaml in Vite project

I want to set an environment variable in github action .yaml. And I can access that variable inside my Vite project run time.
Exp:
# staging.yaml - my github action file
...
env: VITE_INTERNAL = true
...
// index.vue - my Vite project
function myTest(){
console.log(process.env.VITE_INTERNAL) // I hope to get "true" instead of "undefined"
}
Anyone can help me, please. Thanks a lot!
To set an environment variable in a GitHub Action YAML, you can use env, jobs.<job_id>.env, or jobs.<job_id>.steps[*].env:
name: Build
permissions:
contents: read
issues: read
checks: write
pull-requests: write
on: push
# 👇 global env
env:
VITE_INTERNAL: true
jobs:
build:
runs-on: ubuntu-latest
# 👇 or job-level env
env:
VITE_INTERNAL: true
steps:
- uses: actions/checkout#v3
- uses: actions/setup-node#v3
with:
node-version: 18.x
cache: 'npm'
- name: Install dependencies
run: npm i
- name: Build
run: npm run build
# 👇 or step-level env
env:
VITE_INTERNAL: true
To access the environment variable from JavaScript, use import.meta.env.VITE_INTERNAL (not process.env.VITE_INTERNAL).
GitHub demo
You can read the docs here, but to expose env variables, you can do it like the following.
.env
VITE_INTERNAL = true
.yaml
console.log(import.meta.env.VITE_INTERNAL)

Prevent Vercel Deployment on branch push

I have my GitHub Repository linked to my vercel project. Required for deploying changes on a subdomain that's linked to a branch on my git repository. dev.<website>.<tld> is linked to the dev branch. <website>.<tld> is linked to the main branch. Couldn't figure out another way to do this, other than linking to my git repo.
I have a GitHub action that runs tests amongst other things that I want to ensure pass before deployment. But every time I push changes to my production branch it kicks of a vercel deployment, that I want to avoid.
I know there is a Ignored Build Step section in the git settings on vercel, but I'm not sure what to add in the command input in this section?
I've added
[ exit 1 ]
But not sure if this is correct.
Here is my github actions workflow yml file.
name: Deploy Web Application
on:
push:
branches: ["master", "development"]
paths:
- "web/**"
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./web
strategy:
matrix:
node-version: [16.13.0]
steps:
- name: Checkout
uses: actions/checkout#v3
- name: Node Version ${{ matrix.node-version }}
uses: actions/setup-node#v3
with:
node-version: ${{ matrix.node-version }}
cache: "yarn"
cache-dependency-path: "./web/yarn.lock"
- name: Install Dependencies
run: yarn
- name: Build Project
run: yarn build
- name: Run Linting
run: yarn lint
- name: Run Typecheck
run: yarn typecheck
- name: Start Deployment
uses: bobheadxi/deployments#v0.6.2
id: deployment
with:
step: start
token: ${{ secrets.GH_TOKEN }}
env: prod
- name: Deploy to Vercel
uses: amondnet/vercel-action#v20
id: vercel-action
with:
github-token: ${{ secrets.GH_TOKEN }}
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
# if main branch go to --prod environment otherwise nothing for preview environment
vercel-args: "${{ github.ref == 'refs/heads/master' && '--prod' || '' }}"
working-directory: ./web
- name: Update Deployment Status
uses: bobheadxi/deployments#v0.6.2
if: always()
with:
step: finish
token: ${{ secrets.GH_TOKEN }}
status: ${{ job.status }}
deployment_id: ${{ steps.deployment.outputs.deployment_id }}
env_url: ${{ steps.vercel-action.outputs.preview-url }}
You can enable the "Ignored Build Step" field by referring to the
documentation of this feature. If the command returns "0", the
build will be skipped. If, however, a code "1" or greater is
returned, then a new deployment will be built.
With a Script
#!/bin/bash
echo "VERCEL_ENV: $VERCEL_ENV"
if [[ "$VERCEL_ENV" == "production" ]] ; then
# Proceed with the build
echo "✅ - Build can proceed"
exit 1;
else
# Don't build
echo "🛑 - Build cancelled"
exit 0;
fi
With Environment Variables
#!/bin/bash
echo "VERCEL_GIT_COMMIT_REF: $VERCEL_GIT_COMMIT_REF"
if [[ "$VERCEL_GIT_COMMIT_REF" == "staging" || "$VERCEL_GIT_COMMIT_REF" == "main" ]] ; then
# Proceed with the build
echo "✅ - Build can proceed"
exit 1;
else
# Don't build
echo "🛑 - Build cancelled"
exit 0;
fi
With Folders and Workspaces
To build a new deployment considering only a certain folder, you can use the following command:
git diff HEAD^ HEAD --quiet ./packages/frontend/
The above was copied from here (includes more details):
How do I use the "Ignored Build Step" field on Vercel?
Video tutorial:
How to Ignore Build Step on Vercel
Another guide:
Vercel – ignore GitHub branches

How to use github actions bot for testing gradle java

I am trying to implement Github-actions(bot), which runs gradle test when PR has been created.
To assure that my workflow file works as I expected, I explicitly wrote a test method which should cause failure.
#Test
fun thisShouldFail() {
assertEquals(1, 2)
}
When I try testing on my local machine, I get the log below.
> Task :test FAILED
FAILURE: Build failed with an exception.
# More
Above log indicates that there was something wrong in the test codes as I expected it to be.
But then Github actions bot runs this command, the test code result is SUCCESS.
Below is my github workflow yaml file for this action.
name: PullRequestGradleTest
on:
pull_request_target:
types: [labeled]
jobs:
test:
name: GradleTest
runs-on: ubuntu-latest
if: contains(github.event.pull_request.labels.*.name, 'STAGING')
steps:
- name: checkout
uses: actions/checkout#v2
- name: Setup JDK 1.8
uses: actions/setup-java#v2
with:
java-version: '8'
distribution: 'adopt'
- name: Grant Permissions to gradlew
run: chmod +x gradlew
- name: Test
run: gradle test --tests "*"
- name: Test Success
if: success()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "All tests passed.",
event: "APPROVE"
})
- name: Test Fail
if: failure()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "There is something wrong with test codes.",
event: "REQUEST_CHANGES"
})
await github.pulls.update({
...context.repo,
pull_number,
state: "closed"
})
I found that you are using gradle, not gradlew.
name: PullRequestGradleTest
on:
pull_request_target:
types: [labeled]
jobs:
test:
name: GradleTest
runs-on: ubuntu-latest
if: contains(github.event.pull_request.labels.*.name, 'STAGING')
steps:
- name: checkout
uses: actions/checkout#v2
- name: Setup JDK 1.8
uses: actions/setup-java#v2
with:
java-version: '8'
distribution: 'adopt'
- name: Grant Permissions to gradlew
run: chmod +x gradlew
- name: Test
run: ./gradlew test --tests "*"
- name: Test Success
if: success()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "All tests passed.",
event: "APPROVE"
})
- name: Test Fail
if: failure()
uses: actions/github-script#0.2.0
with:
github-token: ${{ github.token }}
script: |
const pull_number = "${{github.event.number}}"
await github.pulls.createReview({
...context.repo,
pull_number,
body: "There is something wrong with test codes.",
event: "REQUEST_CHANGES"
})
await github.pulls.update({
...context.repo,
pull_number,
state: "closed"
})
If you use gradle in the command, it will depend on the machine's environment. In this case, there is a possibility that occurs error because of Gradle version. Therefore, you need to use the project's Gradle which is included with your repo. The way to use is using gradlew scripts.
I also recommend following these three steps to test the branch for the pull request.
Clean -> Assemble(or build) -> Test
Base problem was that if we use pull_request_target event, the action runs on the target branch, which would be the base branch that the PR will be merged into. To solve this problem, I had to explicitly set where this action will run on.
On job => steps
steps:
- name: checkout
uses: actions/checkout#v2
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{github.event.pull_request.head.repo.full_name }}

Bitrise + Detox + React-native - Hello World Example hangs on detox.init

I'm trying to get the react-native "Hello World" app setup with Detox and running on Bitrise.io. I went through the react-native-cli getting started guide and am trying to run the simplest detox test using Detox + Jest on Bitrise with it.
The specific error I'm encountering is the device and element globals not being defined (see log or in the link below). From what I've researched so far, this is caused by detox.init not ever finishing.
Is there some basic config with Bitrise that I'm missing? The detox test command runs locally for me just fine.
I'm using a free Bitrise account, and the project is public. You can see a failed build here: https://app.bitrise.io/build/e7926ddfc759288f#?tab=log
The repo is also public: https://github.com/jamesopti/react-native-test/blob/add_detox/AwesomeProject/e2e/firstTest.spec.js
Thanks in advance!
Bitrise Error Log
Example: should have welcome screen
Example: should have welcome screen [FAIL]
FAIL e2e/firstTest.spec.js (122.008s)
Example
✕ should have welcome screen (8ms)
● Example › should have welcome screen
Timeout - Async callback was not invoked within the 120000ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 120000ms timeout specified by jest.setTimeout.
at mapper (../node_modules/jest-jasmine2/build/queueRunner.js:25:45)
● Example › should have welcome screen
ReferenceError: device is not defined
1 | describe('Example', () => {
2 | beforeEach(async () => {
> 3 | await device.reloadReactNative();
| ^
4 | });
5 |
6 | it('should have welcome screen', async () => {
bitrise.yml
---
format_version: '8'
default_step_lib_source: https://github.com/bitrise-io/bitrise-steplib.git
project_type: react-native
trigger_map:
- push_branch: "*"
workflow: primary
- pull_request_source_branch: "*"
workflow: primary
workflows:
deploy:
description: "## ..."
steps:
- activate-ssh-key#4.0.3:
run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}'
- git-clone#4.0.17: {}
- script#1.1.5:
title: Do anything with Script step
- yarn#0.1.0:
inputs:
- workdir: AwesomeProject
- command: install
- install-missing-android-tools#2.3.7:
inputs:
- gradlew_path: "$PROJECT_LOCATION/gradlew"
- android-build#0.10.0:
inputs:
- project_location: "$PROJECT_LOCATION"
- certificate-and-profile-installer#1.10.1: {}
- xcode-archive#2.7.0:
inputs:
- project_path: "$BITRISE_PROJECT_PATH"
- scheme: "$BITRISE_SCHEME"
- export_method: "$BITRISE_EXPORT_METHOD"
- configuration: Release
- deploy-to-bitrise-io#1.9.2: {}
primary:
steps:
- activate-ssh-key#4.0.3:
run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}'
- git-clone#4.0.17: {}
- yarn#0.1.0:
inputs:
- workdir: AwesomeProject
- command: install
title: Yarn Install
- yarn#0.1.0:
inputs:
- workdir: AwesomeProject
- command: test
title: Unit tests
after_run:
- detox
detox:
steps:
- cocoapods-install#1.9.1:
inputs:
- source_root_path: "$BITRISE_SOURCE_DIR/AwesomeProject/ios"
- npm#1.1.0:
title: Install Global
inputs:
- workdir: "$BITRISE_SOURCE_DIR/AwesomeProject"
- command: install -g detox-cli react-native-cli
- script#1.1.5:
inputs:
- working_dir: "$BITRISE_SOURCE_DIR/AwesomeProject"
- content: |-
#!/usr/bin/env bash
brew tap facebook/fb
export CODE_SIGNING_REQUIRED=NO
brew install fbsimctl
brew tap wix/brew
brew install applesimutils --HEAD
title: Install detox utils
- script#1.1.5:
inputs:
- working_dir: "$BITRISE_SOURCE_DIR/AwesomeProject"
- content: |-
#!/usr/bin/env bash
detox build --configuration ios.sim.debug
title: Detox Build
- script#1.1.5:
inputs:
- working_dir: "$BITRISE_SOURCE_DIR/AwesomeProject"
- content: |-
#!/usr/bin/env bash
detox test --configuration ios.sim.debug --cleanup
title: Detox Test
app:
envs:
- opts:
is_expand: false
PROJECT_LOCATION: AwesomeProject/android
- opts:
is_expand: false
MODULE: app
- opts:
is_expand: false
VARIANT: ''
- opts:
is_expand: false
BITRISE_PROJECT_PATH: AwesomeProject/ios/AwesomeProject.xcworkspace
- opts:
is_expand: false
BITRISE_SCHEME: AwesomeProject
- opts:
is_expand: false
BITRISE_EXPORT_METHOD: ad-hoc
meta:
bitrise.io:
machine_type: elite
Unfortunately, this is a very generic bug and can be caused by multiple things (incompatible OS/jest + detox versions/node + detox versions, etc).
If you're using MacOS, an option you can take in able to check what's going wrong in Bitrise's VM is connecting via Screen Sharing: I'd suggest adding a while someFileDoesntExist (to stop iteration naturally without the abort button) in your current workflow after the packages installation steps (node, detox, jest etc) and then checking if its the same one you're running locally.
If that's not the case, check if the VM is running the same simulator -- phone model && OS version; if its not, then you can specify the simulator & OS version in your detox configuration.
If that also didn't work, I'm not sure what it could be :(

PhantomJS timeout issue when running in headless mode in GitLab CI

I am trying to use GitLab CI to run some client-side unit test written using QUnit. Now to run the Qunit test I am using the grunt-contrib-qunit plugin. To run these tests in headless mode I am using this plugin which hosts it on a localhost server in a console and runs all unit tests. When running this project locally I am successfully able to run all the unit tests but when I checking in my code which kicks of the CI process, on GitLab, it fails on starting the phantomjs server and gives timeout error. I am also providing the jsbin link of the two text files which are basically the output of the unit test from my console. One file is of my local system and another is from the GitLab CI that runs on GitLab website when I check-in my code.
Local Console Output File Dump
Gitlab CI Output Dump
Adding my gitlab-ci.yaml file
image: node:4.2.2
before_script:
- dir
- cd sapui5_repo
- dir
- cd app-with-tests
build:
stage: build
script:
- npm i
- npm run test
cache:
policy: push
paths:
- node_modules
artifacts:
paths:
- built
Also adding my gruntfile if that helps
/* global module */
module.exports = function (grunt) {
grunt.initConfig({
qunit: {
all: {
options: {
timeout: 9000,
urls: [
"http://localhost:9000/webcontent/test/unit/unitTests.qunit.html"
]
}
},
//all: ["webcontent/test/unit/unitTests.qunit.html"],
options: {
timeout: 2000,
}
},
connect: {
options: {
//open: true,
},
first: {
options: {
port: 9000,
//livereload: 3500,
base: "./"
}
},
second: {
options: {
open: {
target: "http://localhost:9000/webcontent"
},
keepalive: true,
port: 9000,
livereload: 3501,
base: "./",
}
}
},
});
grunt.loadNpmTasks("grunt-contrib-connect");
grunt.loadNpmTasks("grunt-contrib-qunit");
grunt.registerTask("test", [
"connect:first", "qunit"
]);
grunt.registerTask("default", [
"connect:second"
]);
};