Я использую шутку для модульного тестирования в react native. Вот моя функция componentWillMount ():
componentWillMount() {
this.setState({ loading: true });
axios.get(SERVER_URL + '/courses')
.then(response => {
this.state.trainingcatalogues = []
this.state.traininglist = []
this.state.Location1 = []
this.state.Category1 = []
this.state.Location2 = ['All']
this.state.Category2 = ['All']
for (var key in response.data) {
if (response.data[key].coursetype === 'Instructor-Led' && response.data[key].status === 'Active' ) {
this.state.Location1.push(response.data[key].location);
this.state.Category1.push(response.data[key].category);
this.state.trainingcatalogues.push(response.data[key]);
this.state.traininglist.push(response.data[key]);
}
}
Я хочу поиздеваться над «ответом» в моем тестовом примере. Он имеет следующий формат:
let response =
{
"data": [
{
"_id": "5acb16701e09ae8abc29e7fb",
"courseName": "Agile Fundamentals420",
"category": "Agile",
"coursetype": "Instructor-Led",
"duration": 22,
"addnote": "contractor",
"status": "Completed",
"registrations": 10
}
]
}
Это мой пример модульного теста:
it('should test the componentwillMount function', () => {
const wrapper = shallow(<Instructor_cata navigation = {navigation}/>);
const instance = wrapper.instance();
const componentWillMountSpy = jest.spyOn(instance,"componentWillMount");
instance.forceUpdate();
instance.componentWillMount();
expect(componentWillMountSpy).toHaveBeenCalled();
});
Как имитировать эти данные ответа в модульном тесте?
@dentemm Подскажите, пожалуйста, как с этим поступить?
Добавлен ответ ниже, чтобы помочь вам начать работу
Вам удалось заставить его работать?





Вам нужно будет имитировать библиотеку Axios, и для этого есть несколько вариантов. Во-первых, есть несколько библиотек, таких как axios-mock-adapter или jest-mock-axios, но вы могли бы просто написать макет самостоятельно, это не так уж и много.
Базовый пример:
// mock.js: custom axios mock file in your tests folder
module.exports = {
get: jest.fn((url) => {
switch (url): {
case '<your_url>/courses':
return Promise.resolve(<your_response_object>)
default:
return Promise.resolve({...})
})
}
};
Просто импортируйте макет в свои тестовые файлы. И вы можете использовать аналогичный подход для других методов axios, таких как post ().
Вам нужно будет издеваться над библиотекой axios