mercredi 5 juin 2019

How to test correct data validation with Mocha using Loopback?

I'm setting up tests for already existing code. I want to test the creation of a database entry for an object, specifically how the create()-Method should behave when incorrect parameters are given. When trying to create the object with intentionally incorrect parameters, the Loopback upsert()-Method (which is used by our create()-Method) throws an error before I can assert the behaviour.

We're using Node, Express and Loopback for the Backend and Mocha with Chai as the testing suite. We're using the Loopback option "validateUpsert:true" in the Model of the object, which supposedly leads to throwing the aforementioned error.

The basic Model looks something like this:

{
  "name": "Field",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "numberOfSpots": {
      "type": "number",
      "required": true
    }
}

So my test case in Mocha looks like the code below. Note the comment next to numberOfSpots:

it('should return null upon entering false data', async() => {
  // Given
  const givenFieldData = {
    numberOfSpots: 'two' // Using text instead of a number
  }

  // When
  const newField = await Field.create(givenFieldData);

  // Then
  assert.isNull(newField);

});

Field.create(givenFieldData) basically calls this Loopback method after transforming givenFieldData into a Field-Object:

FieldModel.upsertWithWhere(where, Field)
    .catch(error => logger.error(error))
    .finally(return null);

Now I would expect that the assert runs but it is actually never executed. The finally block also does not seem to be executed. The console logs something like this:

ERROR (ValidationError/3844 on M): The instance `Field` is not valid. Details: `numberOfSpots` can't be blank (value: NaN).

Now the test fails although the behavior is correct, i.e. the object was not created. I need to find a way to check if the object was (correctly) not created and this should be reflected by a passing test. Thanks!

Aucun commentaire:

Enregistrer un commentaire