简体   繁体   中英

How to test a function which include an async function?

there is a function

function foo(){
  bar('hi',callback)
}

bar is an async function, how to test foo in mocha or other test frameworks?

For this function you can simply return a value. Now based on callback type either you can stub a promise:

 bar.returns('some value', Q.reject({success: false}))

Or maybe a function:

bar.returns('some value', sinon.spy())

PS I haven't tested this. You might wanna read:

http://sinonjs.org/releases/v4.0.0/spies/

http://sinonjs.org/

describe('', function() {
  it('', async function() {
    const result = await foo();
    result.should.equal('hi');
  });
});

Mocha supports async await now. refer the link https://mochajs.org/

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