简体   繁体   中英

use jest mock to run async function in isolation

async await jest mock http request in node.jest

I can write my test like so
it('works with async/await', async () => {
  expect.assertions(1);
  const data = await user.getUserName(4);
  expect(data).toEqual('Mark');
});

but getUserName will be executed and it hit my backend and database, how to mock the function so that my test can be run in isolation?

You need to actually mock the user object. I don't have full context but you probably have something like const User = require('../user.js') . So with jest you can mock this by doing

jest.mock('../user.js')

jest.mock accepts also a callback where you can add there your own implementation but I prefer having a seperate mocks folder where you can keep your own implementation of the mock as it might make the tests a bit more cluttered.

You can check how it's used here where you call jest.mock and then the mock implementation .

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