2017-04-19 3 views
3

농담이농담은 -

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, {...}); 
} 
+1

모듈에'apiGetMethod'가 어떻게 주입 되었습니까? –

+0

'Foo' 컴포넌트 파일의 상단에있는 './api';에서 import {apiGetMethod}를 호출했습니다. –

답변

4

에 대한 api.js 파일을 당신은 조롱해야 어떻게 모의가해야 설정할 수 있습니다 테스트에서 모의 ​​

import { apiGetMethod } from './api' 

jest.mock('./api',() => ({ apiGetMethod: jest.fn() })) 

의 된 구현을 설정할 수 있도록 ./api이 같은 모듈은 가져 mockImplementation를 사용하여 작업 :

apiGetMethod.mockImplementation(() => Promise.resolve('test1234')) 
+0

mock을'__mocks __/api.js'에 넣고'jest '를 호출하여 mock을 생성했습니다. mock ('./ api')'하지만 모의를 끌지는 않습니다. https://facebook.github.io/jest/docs/tutorial-async.html#content –

2

을 경우 안드레아스의 대답은 당신을 위해 작동하지 않았다 @에서 jest.mock 방법. 테스트 파일에서 다음을 시도해 볼 수 있습니다.

const api = require('./api'); 
api.apiGetMethod = jest.fn(/* Add custom implementation here.*/); 

는 내부 Foo 구성 요소를 apiGetMethod 당신의 조롱 버전을 실행해야합니다.

+0

이것은 실제로 내가 결국 무엇을했는지입니다. 구현을 조롱해라.'jest.fn (() => {return ...})' –