Jest - 如何测试承诺的结果

加布

使用 Jest 如何测试在单元测试下的函数中的承诺被解决时执行的步骤?

例子:

// FUNCTION TO TEST
export function functionToTest(url) {
  initSomething().then(() => {
    console.log('YEP, CALLED');
    storeHistory.push(url);
  });
}

// UNIT TEST
import { functionToTest, __RewireAPI__ as rewireUtility } from './funcToTest';

describe('functionToTest', () => {
  let pushSpy;
  beforeEach(() => {
    pushSpy = jest.fn();
    rewireUtility.__set__('storeHistory', { push: pushSpy });
    rewireUtility.__set__('initSomething', () => Promise.resolve());
  });

  it('pushes the given url to history after initializing cordova', () => {
    functionToTest('/sports');
    expect(pushSpy).toHaveBeenCalledTimes(1);
    expect(pushSpy).toHaveBeenCalledWith('/sports');
  });
});

在这种情况下 pushSpy 被调用 0 次(即使日志被打印出来)。我怎样才能正确地测试这个?

加布

用这个解决了:

it.only('pushes the given url to history after initializing cordova', (done) => {
  rewireUtility.__Rewire__('history', { push: (route) => {
        expect(route).toEqual('/sports');
        done();
  } });
  functionToTest('test://sports');
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章