Persist to workspace doesn't run after a failed test command

circle.yml

#1

I’m using CircleCI to run some tests using jest and then run DangerJS in a subsequent job. The idea is that if the tests fail, the test-results.json output will be picked up by danger so a bot can list the failing tests in a comment on the PR.

I’m running the tests in a job, and in the next job that’s running danger, I’m looking to grab the test-results.json file. Initially I was doing

      - persist_to_workspace:
          root: /root/workspace
          paths:
            - coverage
            - test-results.json

in the test job. The only problem is that when the tests fail, the persist_to_workspace command doesn’t seem to run, and I can’t find a way to force it. I don’t want to store_test_results or store_artifacts from what I can see… Any help would be much appreciated.


#2

Am I right in saying that, as a result of the failed test command, the persist step is not reached?

If so, I would run the tests inside a shell script that records the failure in an env var, then returns 0 (successful). Your persist step can then run, and then after that you can have a new step that conditionally throws an error based on the env var.


#3

That worked like a charm, thanks for your help @halfer !


#4

You’re welcome! Would you add a YAML snippet here on how you did it? I reckon that could be useful for a future reader.


#5

Certainly!

jobs:
  execute_test_runner:
    steps:
      - attach_workspace:
          at: /root/workspace
      - run:
          name: Running test suite
          command: |
            if npm run test -- --outputFile test-results.json --json ; then
              echo 'export TESTS_PASS=true' >> $BASH_ENV
            else
              echo 'export TESTS_PASS=false' >> $BASH_ENV
            fi
      # This test runner job never fails. I'm storing the result as an
      # environment variable, but it turns out I don't need to
      # because the danger job will fail if tests are failing.
      # Left it in here just in case it's useful for anyone.
      - run:
          name: Saving test results
          command: |
            cp test-results.json \
              /root/workspace
      - persist_to_workspace:
          root: /root/workspace
          paths:
            - test-results.json

  execute_danger:
    working_directory: /root/project
    steps:
      - attach_workspace:
          at: /root/workspace
      - checkout:
          path: /root/project
      - run:
          name: Copy test results into project
          command: |
            cp ~/workspace/test-results.json \
              ~/project
      - run:
          name: Run danger
          command: npm run danger ci
          # Runs dangerjs with danger-plugin-jest
          # If there are failing tests the plugin will fail this
          # job by reading from test-results.json

#6

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.