【问题标题】:Manual mocks with Jest -- I'm not understanding something用 Jest 手动模拟——我不明白
【发布时间】:2018-06-01 17:58:15
【问题描述】:

我正在学习玩笑,并尝试为 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 _ 文件),它的测试很好。感谢您的时间。

我得到的错误:

  ● 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"
  }
}

谢谢!

【问题讨论】:

    标签: reactjs api unit-testing mocking jestjs


    【解决方案1】:

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

    现在,有像 Enzyme(http://airbnb.io/enzyme/) 这样的工具可以帮助您测试 React 组件。

    你检查过测试 React 应用程序部分的 Jest 吗?特别是 DOM 测试部分?看这里:https://facebook.github.io/jest/docs/en/tutorial-react.html#dom-testing

    回到你的问题,我认为这是因为你在模拟文件中将 fn 作为默认值导出,但在 api 文件中没有这样做。试着把两个相等告诉我!

    【讨论】:

    • 您好,谢谢!我将研究如何测试元素在 dom 上的呈现方式,但我现在仍然只是试图专注于如何进行手动模拟。错误消息保持不变(我意识到我之前给了你稍微错误的错误消息,我很抱歉,从我读到的内容我应该使用与我的组件中命名的相同的 .method 调用):`TypeError:GifContainer.displayGifs不是 Object..it (src/Part_2/GifContainer.test.js:16:23) 处的函数。_tickCallback (internal/process/next_tick.js:109:7`
    • 好的..只关注错误...错误是因为GifContainer是一个类,所以,你需要先实例化它..像container = new GifContainer()这样你可以调用container.displayGifs 然而,这远不是测试 React 组件的正确方法......要删除测试 React 组件的第一步,将 api 文件导入一个哑模块并在那里测试呢?您可以创建一个带有愚蠢函数的新 javascript 模块来调用 api.js。它会更容易测试,你不会受到任何 React 错误的影响
    猜你喜欢
    • 2018-09-16
    • 2019-06-09
    • 2020-01-27
    • 2021-03-14
    • 2017-05-23
    • 2015-04-22
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多