2017-04-19 37 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 ...})' –