농담이농담은 -
apiGetMethod = jest.fn().mockImplementation(
new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
process.nextTick(
() => users[userID] ? resolve(users[userID]) : reject({
error: 'User with ' + userID + ' not found.',
});
);
});
);
그러나 이러한 모의 객체는 함수가 테스트에 직접 호출 할 때 제대로 작동 자신의 문서에 설명 된대로 기능을 조롱 할 수있는 방법을 제공하는 반작용 구성 요소 내에서 호출하는 기능을 모의.
describe('example test',() => {
it('uses the mocked function',() => {
apiGetMethod().then(...);
});
});
그런 반응 물질을 어떻게 조롱 할 수 있습니까?
import { apiGetMethod } from './api';
class Foo extends React.Component {
state = {
data: []
}
makeRequest =() => {
apiGetMethod().then(result => {
this.setState({data: result});
});
};
componentDidMount() {
this.makeRequest();
}
render() {
return (
<ul>
{ this.state.data.map((data) => <li>{data}</li>) }
</ul>
)
}
}
나는 내가이 데이터를 제대로 렌더링하는 테스트 할 수 있도록 그렇게 Foo
구성 요소 내 조롱 apiGetMethod()
구현을 호출을하는 방법을 모른다.
편집 (이 호출되는 함수를 조롱 내부의 구성 요소에 반응하는 방법을 이해하기 위해서 단순화, 인위적인 예입니다) : 선명도
// api.js
import 'whatwg-fetch';
export function apiGetMethod() {
return fetch(url, {...});
}
모듈에'apiGetMethod'가 어떻게 주입 되었습니까? –
'Foo' 컴포넌트 파일의 상단에있는 './api';에서 import {apiGetMethod}를 호출했습니다. –