#javascript #reactjs #mocking #jestjs #spy
#javascript #reactjs #издевательство #jestjs #шпионить
Вопрос:
У меня есть функция handleClick, которая использует scrollBy для элемента, который получает свой первый аргумент с помощью getBoundingClientRect. Я пытаюсь протестировать это с помощью jest / enzyme.
class myClass extends Component {
...
...
handleClick () {
document.getElementById('first-id').scrollBy(document.getElementById('second-id').getBoundingClientRect().width, 0);
}
render() {
return (
<button className="my-button" onClick={this.handleClick()}>scroll</button>
);
}
}
Мой тест:
it('calls scrollBy with correct params', () => {
const props = {};
myClassWrapper = mount(<myClass {...props} />);
const scrollBySpy = jest.fn();
global.document.getElementById = jest.fn(() => ({ scrollBy: scrollBySpy }));
myClassWrapper.find('my-button').simulate('click');
// expect(scrollBySpy).toHaveBeenCalledWith()
});
Я пытаюсь проверить, что scrollBy вызывается с правильными параметрами, но при запуске этого теста я получаю следующую ошибку:
Error: Uncaught [TypeError: document.getElementById(...).getBoundingClientRect is not a function]
Извините, если на этот вопрос уже был дан ответ, но я не смог увидеть ничего, что отвечало бы моему сценарию. Заранее благодарю вас.
Ответ №1:
scrollBy
вызывается для первого результата getElementById
и getBoundingClientRect
вызывается для второго результата getElementById
, поэтому вам нужно будет включить обе функции в объект, который вы возвращаете в макет.
Вот рабочий пример, который поможет вам начать:
import * as React from 'react';
import { mount } from 'enzyme';
class MyClass extends React.Component {
handleClick() {
document.getElementById('first-id').scrollBy(document.getElementById('second-id').getBoundingClientRect().width, 0);
}
render() {
return (
<button className="my-button" onClick={this.handleClick}>scroll</button>
);
}
}
it('calls scrollBy with correct params', () => {
const props = {};
const myClassWrapper = mount(<MyClass {...props} />);
const scrollBySpy = jest.fn();
const getBoundingClientRectSpy = jest.fn(() => ({ width: 100 }));
global.document.getElementById = jest.fn(() => ({
scrollBy: scrollBySpy,
getBoundingClientRect: getBoundingClientRectSpy // <= add getBoundingClientRect
}));
myClassWrapper.find('.my-button').simulate('click');
expect(scrollBySpy).toHaveBeenCalledWith(100, 0); // Success!
});