Skip to content

[Question] How to launch an error in autoLogin custom step #2600

Closed

Description

@rsc1975

I've implemented an autoLogin based on REST calls, to optimize the time in login and check processes, the problem is that when the token is invalid I don't know how to mark the check process as invalid so the workflow continues with login stage, if I throw an Error() the entire autoLogin process is halt due to an unexpected error. All the examples I saw use the existing API based on user interface where the user fill-in the credentials in a form and so on, but I didn't find anything using REST helper.

My autoLogin config:

autoLogin: {
      enabled: true,
      saveToFile: true,
      inject: 'login',
      users: {
        admin: {
          login: async (I) => {
            I.amOnPage('/login');
            await I.loginWithCredentials(adminUser.username, adminUser.password);            
          },
          check: (I) => {
            const token = codeceptjs.store['admin_session'];
            I.validateToken(token);
          },
          fetch: async (I) => {
            const cookie = await I.grabCookie('token');
            return cookie.value;
          },
          restore: (I, sessionToken) => {
            I.amOnPage('/login');
            I.saveTokenData(sessionToken);
          }
        },
     }
   }

The custom validationToken() step is something like:

module.exports = function() {
  return actor({

    async validateToken(token) {
    
      let response = await this.sendGetRequest(`/api/session/validate?token=${token}`);
      
      if (response.status === 200) {
        if (response.data === true) {
          return true;
        }
      }
      throw new Error('Invalid token !!');
    }
});

As (ugly) workaround I've got the following code in autoLogin.check implementation:

check: async (I) => {
  console.log('admin.check');
  const token = codeceptjs.store['admin_session'];
  const isValid = await I.validateToken(token);
  if (!isValid) {
    I.see("NOTHING TO SEE HERE, so It'll fail");
  }
},

By the way, I launched the same question in StackOverflow with a bounty, but without luck by the moment.

Activity

  1. brunoklein commented on Sep 28, 2020

    @brunoklein

    Hey Roberto! How about use the assert.fail method? It will fail your entire Scenario and you can customize the message!

    const assert = require("assert");
    
    module.exports = function() {
      return actor({
    
        async validateToken(token) {
          let response = await this.sendGetRequest("/api/session/validate?token=${token}");
          if (response.status !== 200 || response.data !== true) {
              assert.fail("Invalid token!");
          }
        }
    });
    

    Check method:

    check: async (I) => {
      console.log('admin.check');
      const token = codeceptjs.store['admin_session'];
      await I.validateToken(token);
    }
    
  2. rsc1975 commented on Sep 28, 2020

    @rsc1975
    Author

    Hi @brunoklein , assert.fail() doesn't work, the result is similar to throw Error()in this case.

    (node:2245) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Failed
        at Object.validateToken (/home/rob/git/QO/HEMERA/hemera-tests-e2e/hemera/api/session.js:59:10)
        at processTicksAndRejections (internal/process/task_queues.js:97:5)
        at async Object.check (/home/rob/git/QO/HEMERA/hemera-tests-e2e/codecept.conf.js:84:29)
        at async loginFunction (/home/rob/git/QO/HEMERA/hemera-tests-e2e/node_modules/codeceptjs/lib/plugin/autoLogin.js:271:7)
    (node:2245) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
    (node:2245) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    

    In other words, the whole Scenario is marked as failure, because this is like an unexpected error, the autoLogin plugin has a workflow, explained in https://codecept.io/plugins/#autologin, but the workflow doesn't continue when check stage fails, the expected result is to continue with the login stage where I get a new token because the existing one is invalid.

  3. brunoklein commented on Sep 28, 2020

    @brunoklein

    Which node and codeceptjs version are you using?

  4. rsc1975 commented on Sep 28, 2020

    @rsc1975
    Author
        "codeceptjs": "^2.6.10",
        "axios": "^0.20.0",
        "puppeteer": "^5.3.0",
        "rosie": "^2.0.1",
        "webdriverio": "^6.5.0"
  5. locked and limited conversation to collaborators on Sep 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions