0

My application code to test:

create(params) {
  let result = {};
  try {
    result = await this.db.query('/* some query */');
  } catch (e) {
    throw new Error('Error creating User', e);
  }
  return this._getById(result.insertId);
}

I have the _getById method in the same class which does exactly what it says...

And my current test (running through Ava):

test('it should create a user', async t => {
  const db = mock({
    query: () => {
    },
  });
  const userObj = {
        // some params
  };
  const user = new Users({
    db: db.object,
  });
  const call = {
    request: userObj,
  };
  const result = await user.create(call);
    // test?
});

If I try and test anything based off of the result variable, ie. the newly created User, I receive the error "Cannot read property 'insertId' of undefined". What is my best option with Sinon to test that this create method will return a newly created "user"?

benhowdle89
  • 36,900
  • 69
  • 202
  • 331

1 Answers1

0

I think that you have the "Cannot read property 'insertId' of undefined" because the following mock doesn't return something

const db = mock({
  query: () => {
  },
});

If you return something like that

const db = mock({
  query: () => {
    return {
      username: "username"
    }
  },
});

and in the test the result will have the value and you should be able to use expect to check if you have the expected result:

{
  username: "username"
} 

The problem in this specific test starts when the mock does not return something and also calling mock overrode the value that you assigned here

let result = {};
Stavros Zavrakas
  • 3,045
  • 1
  • 17
  • 30