2

我正在尝试模拟 graphql API 以测试反应应用程序但面临问题

处理程序是:

import { graphql } from 'msw'
    
export const postsGql = [
  {
    userId: 1,
    id: 1,
    title: 'first post title',
    body: 'first post body',
  },
  {
    userId: 2,
    id: 5,
    title: 'second post title',
    body: 'second post body',
  }
]

定义捕获相应请求并返回模拟数据的处理程序。

export const graphqlHandlers = [
  graphql.query('posts', async(req, res, ctx) => {
    return res(
      ctx.data(
        postsGql,
      ),
    )
  }),
]

我的测试文件:

    it('Should return posts when clicking fetch with graphql button', async() => {
  render(<ApolloProvider client={client}>
    <App />
  </ApolloProvider>)

  expect(screen.getByRole('heading', { name: 'MSW Testing Library Example', level: 1 })).toBeDefined()

  userEvent.click(screen.getByRole('button', { name: 'Fetch Posts GraphQL' }))

  await waitForElementToBeRemoved(() => screen.queryByLabelText('loading'))

  postsGql.forEach((posts) => {
    expect(screen.getByRole('heading', { name: posts.title, level: 2 })).toBeDefined()
    expect(screen.getByText(posts.body)).toBeDefined()
  })
})

但遇到了这个错误:

Missing field 'posts' while writing result [
  {
    "userId": 1,
    "id": 1,
    "title": "first post title",
    "body": "first post body"
  },
  {
    "userId": 2,
    "id": 5,
    "title": "second post title",
    "body": "second post body"
  }
]

我将不胜感激任何帮助谢谢

4

0 回答 0