Jest - 如何测试承诺的结果
Jest - how to test outcome of promise
如何使用 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');
});
如何使用 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');
});