Jest.js 监视模拟服务工作者(msw)?

yws3nbqq  于 11个月前  发布在  Jest
关注(0)|答案(3)|浏览(175)

在观看了this example如何使用它来测试React应用程序中的API调用之后,我开始使用msw (mock service worker)
我们有没有办法监视那个假服务员?
举例来说:

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
})

字符串
要测试的组件如下所示:

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上的间谍

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])
})

kwvwclae

kwvwclae1#

mswjs的开发人员真的很好,很乐于助人。他们花了很多时间来建议我如何处理它。

TLDR;

我得到的当前工作测试很好-只是建议了jest.fn()的替代方案-我确实喜欢他们建议的可读性:

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) {
    // Consider a missing `method` query parameter as a bad request.
    return res(ctx.status(400))   }

  // Depending on your logic, you can also check if the value of the `method`   // parameter equals to "flickr.photos.search".

  return res(ctx.json({ successful: 'response' })) })


现在,如果您的应用在请求URL中错过了方法查询参数,它将获得400响应,并且在这种不成功响应的情况下不应该调用setPhotos回调。

c3frrgcw

c3frrgcw2#

如果你想避免mocking,你可以监视axios.get并Assert它被正确调用了。

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)
})

字符串

7rfyedvj

7rfyedvj3#

您可以创建一个jest.fn()mock并使用msw来侦听请求。

const getRequestSpy = () => {
  const requestSpy = jest.fn();
  server.events.on('request:start', async (request) => {
    if (
      request.method === 'GET' &&
      matchRequestUrl(new URL(request.url), 'https://api.flickr.com/services/rest/?method=flickr.photos.search')
    ) {
      requestSpy();
    }
  });
  return requestSpy;
};

字符串
然后在测试中:

describe('TestSuite', () => {
  let requestSpy: jest.Mock;
  beforeEach(() => {
    requestSpy = getRequestSpy();
    server.use(
      rest.get('https://api.flickr.com/services/rest/?method=flickr.photos.search', (_, res, ctx) => {
        return res(ctx.status(200));
      })
    );
  })

  afterEach(() => {
    server.events.removeAllListeners();
  })

  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();

    expect(requestSpy).toHaveBeenCalledTimes(1);

  });
});


然而,他们在docs中确实提到了你应该避免请求Assert,但有时候,没有其他办法。

相关问题