2017-04-19 84 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(...); 
    }); 
}); 

如果我有一個React組件定義爲這樣,我該如何嘲笑它?

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文件爲了清楚

// api.js 
import 'whatwg-fetch'; 

export function apiGetMethod() { 
    return fetch(url, {...}); 
} 
+1

如何將'apiGetMethod'注入到模塊中? –

+0

'從'./api'導入{apiGetMethod};'在'Foo'組件文件的頂部 –

回答

4

你必須嘲笑./api模塊這樣並將其導入,您可以設置的模擬

import { apiGetMethod } from './api' 

jest.mock('./api',() => ({ apiGetMethod: jest.fn() })) 
在您的測試

的實行可以設置如何模擬應使用mockImplementation工作:

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

我通過將它放入'__mocks __/api.js'中,然後調用'jest。模擬('./ 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.*/); 

這應該執行apiGetMethod你嘲笑版本里面你Foo組件。

+0

這實際上是我最終做,嘲笑裏面的實現:'jest.fn(()=> {return ...})' –