首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >监视模拟服务人员(msw)?

监视模拟服务人员(msw)?
EN

Stack Overflow用户
提问于 2020-08-14 15:54:44
回答 2查看 3.1K关注 0票数 6

在看过如何使用this example在React应用程序中测试msw (mock service worker)调用之后,我开始使用它。

我们有没有办法监视这个模拟的服务人员?

例如:

代码语言:javascript
复制
import React from 'react'
import { render, act, await } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { rest } from 'msw'
import { setupServer } from 'msw/node'

import SearchBox from '.'

const fakeServer = setupServer(
  rest.get(
    'https://api.flickr.com/services/rest/?method=flickr.photos.search',
    (req, res, ctx) => res(ctx.status(200), ctx.json({ data: { photos: { photo: [] },},}))
  )
)

beforeAll(() => {fakeServer.listen()})
afterEach(() => {fakeServer.resetHandlers()})
afterAll(() => fakeServer.close())

test('it calls Flickr REST request when submitting search term', async () => {
  const { getByLabelText } = render(<SearchBox />)
  const input = getByLabelText('Search Flickr')
  const submitButton = getByLabelText('Submit search')

  await act(async () => {
    await userEvent.type(input,'Finding Wally')
    await userEvent.click(submitButton)
  })

  await wait()

  // TODO: assert that the fakeServer was called once and with the correct URL
})

要测试的组件如下所示:

代码语言:javascript
复制
import React, { useState } from 'react'
import axios from 'axios'

import './index.css'

function SearchBox({ setPhotos }) {
  const [searchTerm, setSearchTerm] = useState('')

  const handleTyping = (event) => {
    event.preventDefault()
    setSearchTerm(event.currentTarget.value)
  }

  const handleSubmit = async (event) => {
    event.preventDefault()
    try {
      const restURL = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${
        process.env.REACT_APP_API_KEY
      }&per_page=10&format=json&nojsoncallback=1'&text=${encodeURIComponent(
        searchTerm
      )}`
      const { data } = await axios.get(restURL)
      const fetchedPhotos = data.photos.photo
      setPhotos(fetchedPhotos)
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <section style={styles.container}>
      <form action="" method="" style={styles.form}>
        <input
          aria-label="Search Flickr"
          style={styles.input}
          value={searchTerm}
          onChange={handleTyping}
        />
        <button
          aria-label="Submit search"
          style={styles.button}
          onClick={handleSubmit}
        >
          SEARCH
        </button>
      </form>
    </section>
  )
}

我有一个可以工作的测试,但我觉得它倾向于实现测试,因为它在setPhotos上使用了间谍

代码语言:javascript
复制
test('it calls Flickr REST request when submitting search term', async () => {
  const fakeSetPhotos = jest.fn(() => {})
  const { getByLabelText } = render(<SearchBox setPhotos={fakeSetPhotos} />)
  const input = getByLabelText('Search Flickr')
  const submitButton = getByLabelText('Submit search')

  await act(async () => {
    await userEvent.type(input, 'Finding Walley')
    await userEvent.click(submitButton)
  })

  await wait()

  expect(fakeSetPhotos).toHaveBeenCalledWith([1, 2, 3])
})
EN

回答 2

Stack Overflow用户

发布于 2020-08-17 19:50:54

mswjs的开发人员真的很好,很乐于助人。他们从容不迫地to advice我如何接近它。

TLDR;

我目前得到的工作测试很好-只是推荐了一个jest.fn()的替代品-我确实喜欢他们的建议的可读性:

代码语言:javascript
复制
test('...', async () => {
  let photos

  // Create an actual callback function
  function setPhotos(data) {
    // which does an action of propagating given data
    // to the `photos` variable.
    photos = data
  }

  // Pass that callback function as a value to the `setPhotos` prop
  const { getByLabelText } = render(<SearchBox setPhotos={setPhotos} />)

  // Perform actions:
  // click buttons, submit forms

  // Assert result
  expect(photos).toEqual([1, 2, 3])
})

我想测试的另一件事是它实际上调用了一个有效的REST URL。

您可以在响应解析程序中反映无效的查询参数。如果查询参数丢失/无效,您的真实服务器将不会生成预期的数据,对吗?所以使用MSW,你的“真实服务器”就是你的响应解析器。检查该查询参数的存在或值,并在该参数无效的情况下引发错误。

rest.get('https://api.flickr.com/services/rest/?method=flickr.photos.search',(req,res,ctx) => { const method = req.url.searchParams.get('method') if (!method) { //将缺少的method查询参数视为错误请求。return res(ctx.status(400)) } //根据您的逻辑,还可以检查method //参数的值是否等于"flickr.photos.search“。返回res(ctx.json({ successful:'response‘})) }

现在,如果您的应用程序缺少请求URL中的方法查询参数,它将得到一个400响应,并且在这种不成功响应的情况下不应该调用setPhotos回调。

票数 5
EN

Stack Overflow用户

发布于 2020-08-16 04:55:19

如果你想避免模仿,你可以监视axios.get并断言它被正确调用了。

代码语言:javascript
复制
test('it calls Flickr REST request when submitting search term', async () => {
  const getSpy = jest.spyOn(axios, 'get');
  const { getByLabelText } = render(<SearchBox />)
  const input = getByLabelText('Search Flickr')
  const submitButton = getByLabelText('Submit search')

  await act(async () => {
    await userEvent.type(input,'Finding Wally')
    await userEvent.click(submitButton)
  })

  await wait()

  expect(getSpy).toHaveBeenCalledTimes(1)
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63408769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档