Search code examples
node.jsamazon-web-servicesaws-codepipelineaws-codebuildaws-code-deploy

AWS not stopping when unitest fails in the codebuild


I am doing a very simple CI/CD using codepipeline with (codeCommit, codebuild, codeDeploy).

I have a simple node.js app that has a unittest like this below

const Allsayings = require('./testAllsayings');
function logPass(tName){
    console.log("PASS - " + tName);
}
function logFail(tName){
    console.log("FAIL - " + tName )
}
// T01 - Search for a saying and succeed
let say01 = new Allsayings();
say01.addQuote("Everyone is looking for something.");
say01.addQuote("Let's try to figure this out together, so help me please");
let output01 = aq01.findSaying("Not here");
if (output01.search("Before you embark") > -1){
    logPass("T01");
} else {
    logFail("T01");
}

I want that when the unit test fails it halt/stop the deployment or the progression of the pipeline.

my byuildspec

version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 16
    commands:
      - echo Installing
  pre_build:
    commands:
      - echo Installing source NPM dependencies.
      - cd serverSide
      - npm install
  build:
    commands:
      - echo Build started on `date`
      - npm install pm2@latest -g
        # buildspec is able to get into your servSide file?
      - ls
      - echo "for debugging ... starting test"
      - node testAllsayings.js
      - echo "test is successful ... "
  post_build:
    commands:
      - echo Build completed on `date`
artifacts:
  files:
    - '**/*'

However, my problem is that when I run codepipeline the codebuild completes successfully despite I made my unittest fail and here is a part of the codebuild log


[Container] 2022/10/03 00:45:05 Running command echo "for debugging ... starting test"
for debugging ... starting test

[Container] 2022/10/03 00:45:05 Running command node testAllsayings.js
Fail - T01


[Container] 2022/10/03 00:45:05 Running command echo "test is successful ... "
test is successful ... 

I read this, and I moved the command node testAllsayings.js to the pre_build stage, but still everything worked without stopping the build stage or deployment stage.


Solution

  • So I found a solution. For code build to catch the error from the unittest, the function has to exist with one. So I added this line of code and now code build stops when the unittest fails.

    function logFail(tName){
        console.log("FAIL - " + tName )
          process.exitCode(1);
    
    }