简体   繁体   中英

how do I mock objects and their methods in javascript

I am having trouble unit testing the javascript function listEntities. The difficulty lies in the mocking/stubbing. The documentation for javascript mocking/stubbing libraries is a mess. I am hoping someone with experience can show me the way. Here is the code:

export const listEntities = (kind, googleDatastoreFactory) => {
  const datastore = googleDatastoreWrapperFactory();
  const query = datastore.createQuery(kind);
  return datastore.runQuery(query)
    .then(results => (results[0]));
};

export const googleDatastoreFactory = () => { 
    const Datastore = require('@google-cloud/datastore');
    return Datastore();
};

Here is my attempt:

describe('datastore api', () => {
  describe('listEntities', () => {
    const mockedGoogleDatastore = JsMockito.mock(GoogleDatastore);
    JsMockito.when(mockedGoogleDatastore).runQuery('query').thenReturn(new Promise(resolve => resolve(['result'])));
    JsMockito.when(mockedGoogleDatastore).createQuery('Test').thenReturn('query');
    const googleDatastoreFactory = () => (mockedGoogleDatastore);
    test('should return list of items', () => {
      listEntities('Test', googleDatastoreFactory).then(result => console.log(result));
    });
  });
});

Here is my error:

  ● datastore api › listEntities › encountered a declaration exception

    TypeError: _jsmockito2.default.mock is not a function

      at Suite.<anonymous> (app/api/datastore.api.test.js:7:60)
      at Suite.<anonymous> (app/api/datastore.api.test.js:6:3)
      at Object.<anonymous> (app/api/datastore.api.test.js:5:1)
          at Generator.next (<anonymous>)
          at Promise (<anonymous>)
          at Generator.next (<anonymous>)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

I ended up not using a mocking library/framework. I just created a dumby class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM