docs icon indicating copy to clipboard operation
docs copied to clipboard

"Testing Best Practices For Rules" does not specify how to mock `UnauthorizedError`

Open zzbennett opened this issue 5 years ago • 1 comments

Description

The Testing Best Practices for Rules page is a great resource for how to setup unit tests on Rules (and other custom Auth0 scripts). It would be great if it could include some sample code for how to mock the UnauthorizedError as well. My Rules ensure certain properties are set on the user object, and if they are not, authentication fails, thus I am return new UnauthorizedError(...) in my callback. But this fails in the unit test because

ReferenceError: UnauthorizedError is not defined

Reproduction

Follow the instructions on Testing Best Practices for Rules. Use auth0's UnauthorizedError in the callback.

Environment

n/a

zzbennett avatar Jul 29 '20 20:07 zzbennett

FWIW I was able to get this working by using this as my test runner:

class UnauthorizedError {
  constructor(msg){
    console.log(msg);
  }
  getMsg() {
    return this.msg;
  }
}

const sandBox = vm.createContext({UnauthorizedError});
const code = "(()=>{return " + fs.readFileSync(filePath) + " })();";

vm.runInNewContext(
  code, sandBox, {
    // filename for stack traces
    filename: path.basename(filePath),
    displayErrors: true
  }
)(
  user,
  context,
  function callback(err, user, context) {
    if (expectedErr == null) {
      expect(user).toEqual(expectedUser)
      expect(context).toEqual(expectedContext)
    } else {
      expect(err.constructor.name).toEqual('UnauthorizedError')
      expect(err.getMsg()).toEqual(expectedErr)
    }
  }
);

zzbennett avatar Jul 29 '20 21:07 zzbennett