用Jest手动模拟 - 我不理解某些东西

时间:2018-06-01 17:58:16

标签: reactjs api unit-testing mocking jestjs

我正在学习开玩笑,并尝试为api做手动模拟,我错过了一些东西。

我正在嘲笑对giphy的api号召。我看到了很多不同的手动模拟语法,不幸的是,它们现在对我来说没有多大意义。我一直在尝试与https://hackernoon.com/api-testing-with-jest-d1ab74005c0ahttps://facebook.github.io/jest/docs/en/tutorial-async.html一起编码,但我被卡住了。

我有一个名为GifListContainer的组件,它显示3个gif,有搜索功能,我只想要一个手工模拟假数据来学习。

我正在使用create-react-app,我看到很多人使用isomorphic-fetch和其他软件包,但是由于jest是内置的,我不能在不添加任何其他内容的情况下执行此操作吗?

我无法弄清楚如何手动编写模拟,我觉得我错过了一些简单的东西。如果我不使用mock(使用不同的测试语法,因为我没有测试_ mock _文件),它测试正常。感谢您的时间。

我得到的错误:

  ● should load gifs
    TypeError: GifContainer.api is not a function
      at Object.<anonymous>.it (src/Part_2/GifContainer.test.js:10:23)
  ✕ should load gifs (6ms)

GifListContainer.js

import {gifApi} from './api'
class GifListContainer extends Component {
  state = {
    gifs: []
  };  
  componentDidMount() {
    this.displayGifs('coding');
  } 
  displayGifs = (query) => {
    gifApi(query)
      .then(res => res.json())
      .then(json => {
        let firstThreeGifs = json.data.slice(0, 3);
        let urls = firstThreeGifs.map(
          gif => gif.images.original.url.split("?")[0]
        );
        this.setState({
          gifs: [...urls]
        });
      });
  };
    //after this there's a search function and the render and such.

api.js

const urlPartOne = "http://api.giphy.com/v1/gifs/search?q="
const urlPartTwo = "&api_key=UE0dCN2WofIwVF0RPbpHo0Lz0k9VhqdG"
const gifApi = (query) => {
  return fetch(urlPartOne + query + urlPartTwo)
}
export {gifApi}

GifContainer.test.js

import React from 'react'
let mockFunction = jest.mock('./api.js');
import * as GifContainer from './GifContainer';
it('should load gifs', () => {
  return GifContainer.displayGifs('sunshine')
  .then(data => {
  expect(data).toBeDefined()
  expect(data.entity.data.type).toEqual('gif')
  })
})

_ 模拟 _ / api.js 我真的只是没有得到如何写这个。

const fs = require('fs')
const api = (query) => new Promise((resolve, reject) => {
fs.readFile(`./src/Part_2/__mockData__/query.json`, 'utf8', (err, data) => {
if (err) reject(err)
  resolve({ entity: JSON.parse(data) })
  })
})
export default api

然后在文件夹_ mockData _ / sushine.json

中模拟数据
/* http://api.giphy.com/v1/gifs/search?q=sunshine&api_key=UE0dCN2WofIwVF0RPbpHo0Lz0k9VhqdG */
{
  "data": [
    {
      "type": "gif",
    }
  ],
  "meta": {
    "status": 200,
    "msg": "OK",
    "response_id": "5b11716a33554c732e0ddf42"
  }
}

谢谢!

1 个答案:

答案 0 :(得分:0)

我不这么认为问题出在模拟本身上。   实际上,首先你需要改进你做反应单元测试的方式。

如今,有一些像酶(http://airbnb.io/enzyme/)这样的工具可以帮助你测试React组件。

您是否检查过Jest的“测试反应应用”部分?特别是DOM测试部分?看看这里:https://facebook.github.io/jest/docs/en/tutorial-react.html#dom-testing

回到你的问题,我认为是因为你在模拟文件中将fn导出为默认值,但是没有在api文件上完成。尽量让两者平等,让我知道!

相关问题