2017-11-21 5 views
0

私はjestと私のapi呼び出しをモックしようとしていますが、何らかの理由で動作しません。なぜ私は本当に理解していない。誰でもアイデアがありますか?どうやってapiコールを模擬するのですか

(テストは、元のAPI呼び出し機能ではなくモックを呼んでおく)

私test.js

import { getStuff } from '../stuff'; 
import * as api from '../../util/api'; 

describe('Action getStuff',() => { 
     it('Should call the API to get stuff.',() => { 
      api.call = jest.fn(); 
      getStuff('slug')(() => {},() => {}); 
      expect(api.call).toBeCalled(); 
      jest.unmock('../../util/api.js'); 
     }); 
}); 

stuff.js Reduxのアクション

import api from '@util/api'; 
import { STUFF, API } from '../constant'; 


export const getStuff = slug => (dispatch, getState) => { 
    const state = getState(); 
    api.call(API.STUFF.GET, (err, body) => { 
     if (err) { 
      console.error(err.message); 
     } else { 
      dispatch({ 
       type: STUFF.GET, 
       results: body, 
      }); 
     } 
    }, { 
     params: { slug }, 
     state 
    }); 
}; 

答えて

1

輸入は不変ですだから、それは動作しません、あなたはモジュール全体を模倣する必要があります。 __mock__ディレクトリまたは単に

jest.mock('../../util/api'); 
const { call } = require('../../util/api'); 
call.mockImplementation(() => console.log("some api call")); 
+0

どのようなアイデアをテストできますか? (エラー、ボディ)=> { if(err){ console.error(err.message); } else { ディスパッチ({ タイプ:STUFF.GET、 結果:body、 }); } } – Alexandre

+0

このメソッドの問題点は何ですか?それがディスパッチならば、それをメソッドに提供しているものを何でも模倣する必要があります。 – Axnyff

+0

Thx、私は何をしたいのか分かったと思います。api.call = jest.fn((ルート= ''、コールバック)=> { コールバック: 'some error'}、null); }); – Alexandre

関連する問題