【问题标题】:How to Test Apollo mutation with one variable set to random?如何测试一个变量设置为随机的 Apollo 突变?
【发布时间】:2021-12-06 00:48:24
【问题描述】:

我正在使用 Appolo Mock 提供程序测试我的组件。但是,我有这个突变查询,其中我的一个变量设置为随机 UUID。我怎么能测试它?由于我的查询与我的模拟不匹配,它给了我一个没有模拟响应的错误,请帮助 tnx。

组件

const [createMenuProduct, { loading }] = useMutation(CREATE_MENU_PRODUCTS);

createMenuProduct({
  variables: {
    menuId: menuId,
    id: uuid(),
    productId: selectedProduct,
  },
});

测试模拟

 {
    request: {
      query: CREATE_MENU_PRODUCTS,
      variables: {
        menuId: menuId,
        id: uuid(),
        productId: '4b1b6048-6cb1-46e0-ab4d-80fd11ebeacb',
      },
    },
    result: {
      data: {
        insertMenuProducts: {
          returning: [
            {
              menu_id: 'b591993d-af18-4bf5-88ad-26f08691afc7',
              product_id: '4b1b6048-6cb1-46e0-ab4d-80fd11ebeacb',
              product: {
                variant: {
                  id: '04befbe6-9635-4dde-abc2-673af13eb462',
                  isDeleted: false,
                  productVariantAddOns: [],
                },
              },
            },
          ],
        },
      },
    },
  },

由于我无法将我的模拟变量与预期的值匹配,目前我遇到了这个错误

【问题讨论】:

  • uuid() 来自哪里?

标签: reactjs react-apollo react-testing-library


【解决方案1】:

你可以mockuuid()返回的值与模拟中的相同

const uuidVariable = 'mocked-uuid';

...
{
  request: {
    query: CREATE_MENU_PRODUCTS,
    variables: {
      menuId: menuId,
      id: uuidVariable,
      productId: '4b1b6048-6cb1-46e0-ab4d-80fd11ebeacb',

...

在你的测试中

import uuid from 'uuid/v4';
jest.mock('uuid/v4');

describe('some component', () => {
  it('call mutation', () => {
    uuid.mockImplementation(() => uuidVariable);
    // here render component and interact to fire the mutation
  });  
});

【讨论】:

  • 您好需要通过该模拟,因为在此之后我仍然有其他突变,目前我遇到此错误 查询没有更多模拟响应:突变 insertMenuProducts
  • @EileenDeGuzman 即使我在回答中提出了更改,您是否仍然收到错误?
猜你喜欢
  • 2019-03-22
  • 2022-12-01
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多