@alex_vma

Как протестировать console.error внитри функции(JEST)?

Есть функция которую я тестирую:
function autocomplete <T extends TArguments>(config: T, cb: (place: TResponse) => void): void {
    if (!config) console.error('autocomplete can\'t have empty config or must have config as an argument.');
    if (Object.keys(config).length === 0) console.error(' autocomplete can\'t have an empty config.');

    // @ts-ignore
    const api = new google.maps.places.Autocomplete(
        document.getElementById(config.inputId),
        config.options,
    );

    api.addListener('place_changed', () => {
        cb && cb(api.getPlace());
    });
}


И тест для нее:
import {autocomplete} from '../src';
import {initialize} from "@googlemaps/jest-mocks";
import '@testing-library/jest-dom'

declare var google: any;

jest.mock('../src/lib/autocomplete.ts');

describe('Autocomplete is mocked', () => {
    beforeEach(() => {
        initialize();
    })

    afterEach(() => {
        jest.clearAllMocks()
    })

    it('Init test', () => {
        expect(new google.maps.places.Autocomplete(null)).toBeTruthy();
    })

    it('Correct custom Google places api', () => {
        autocomplete({
            inputId: 'input',
            options: {
                componentRestrictions: { country: ['CA', 'US'] },
            }
        }, (value) => {
            expect(value).toBe([])
        })

        expect(autocomplete).toBeCalledTimes(1)
    })

    it('Without config: should log an error', () => {
        const error = jest.spyOn(global.console, 'error').mockImplementation(() => {})

        autocomplete({
            inputId: 'input',
            options: {}
        }, (value) => {
            expect(value).toBe([])
        })
        // expect(autocomplete).toBeCalledTimes(1)
        // expect(error).toEqual('a')
        expect(error).toHaveBeenCalledWith(
            expect.stringContaining('autocomplete can\'t have empty config or must have config as an argument.'),
        )

        error.mockRestore();
    })
})

второй тест не выбрасывает console.error и я получаю:

Error: expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: StringContaining "autocomplete can't have empty config or must have config as an argument."

Number of calls: 0
  • Вопрос задан
  • 167 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы