mercredi 27 avril 2016

Javascript Testing With Unique ID's

I am kinda new to testing javascript and I was wondering what is the best way to go about testing something where a unique ID is generated.

EDIT:

I don't really want to test the ID I want to make sure that the action returns the right results when the createQuestion function is called. But the test will fail because the ID will never match since it is generated in the function.

My current code looks like this.

//------- Action Creator --------//

export const createQuestion = function (inputType) {
  const hasOptions = /radio/g.test(inputType);
  return {
    type: types.CREATE_QUESTION,
    question: {
      id: uuid.v1(),
      priority: null,
      title: null,
      tip: null,
      required: false,
      isSaved: false,
      hasOptions: hasOptions,
      input: {
        type: inputType,
        options: []
      }
    }
  };
};


//------- TESTS --------//
test('Question Actions', nest => {

  nest.test('Create Question', function (assert) {
    const msg = 'Questions was Created';

    const question = {
      id: 1,
      priority: null,
      title: null,
      tip: null,
      required: false,
      isSaved: false,
      hasOptions: false,
      input: {
        type: 'text',
        options: []
      }
    };

    const expectedAction = {
      type: types.CREATE_QUESTION,
      question
    };


    const actualAction = actions.createQuestion('text');
    assert.deepEqual(actualAction, expectedAction, msg);
    assert.end();
  });

Since the Unique Id is generated in the Action Creator it is impossible to mock unless I change the ID after the function returns with the action.

With something like this

const changeUUID = obj => {
  const newobj = {...obj};
  newobj.question.id = 1;
  return newobj;
};

Aucun commentaire:

Enregistrer un commentaire