在 React 应用程序中使用 Jest 模拟服务方法

标点符号

我正在使用 React 和 Typescript 和 Jest 进行单元测试。没有使用酵素。

我正在尝试了解 Jest 的模拟功能,特别是确定某些错误。

我使用带有打字稿的 create-react-app 创建了一个反应应用程序,即

npx create-react-app my-app --template typescript

我的下一步是在 src 目录中创建以下内容。

// services/serviceResponse.ts

export interface ServiceResponse {
    label: string;
    id: string;
  }

// services/myservice.ts

import { ServiceResponse } from "./serviceResponse";

const cannedServiceResponse: ServiceResponse[] = [
    {
        label: 'label1',
        id: 'id1',
    },
    {
        
        label: 'label2',
        id: 'id2',
    },
]

async function GetServiceData(): Promise<ServiceResponse[] | Error> {
    return cannedServiceResponse;
}
  
export default {
    GetServiceData,
};
  
// components/mycomponent.tsx
import React, { useState, useEffect } from 'react';
import myservice from '../services/myservice';
import { Row } from 'react-bootstrap';
import { ServiceResponse } from '../services/serviceResponse';

export const MyComponent = () => {
    const [data, setData] = useState<ServiceResponse[] | undefined>();

    useEffect(() => {
        const fetchData = async () => {
        const serviceData = await myservice.GetServiceData();
        if (!(serviceData instanceof Error)) {
            setData(serviceData);
        }
        };

        fetchData();
    }, []);

    if (!data) {
        return <></>;
    }

    return (
        <>
            <Row xs={1} md={4} className="col-lg-12">
            </Row>
        </>
    );
};

然后我想通过模拟从服务方法返回的数据来对组件进行单元测试GetServiceData我的测试组件代码是

// components/mycomponents.test.tsx
import React from 'react';
import TestRenderer from 'react-test-renderer';
import { MyComponent } from './mycomponent';
import myservice from '../services/myservice';
import { Row } from 'react-bootstrap';
import { ServiceResponse } from '../services/serviceResponse';

const mockData: ServiceResponse[] = [
  { label: 'a', id: 'b'},
  { label: 'f', id: 'g'},
];

describe('mycomponent', () => {
  
  it('MyComponent returns data', () => {
    jest.spyOn(myservice, 'GetServiceData').mockImplementation(
      () =>
        new Promise<ServiceResponse[]>((resolve) => {
          resolve(mockData);
        })
    );

    const component = TestRenderer.create(<MyComponent />);
    const componentInstance = component.root;
    console.log(component.toJSON());
    // TODO - Add an expect line here for assertion
  });
});

问题是 jest.spyOn() 不会模拟数据。我也尝试使用以下方法

jest.mock('../services/myservice', () => ({
  GetServiceData: jest.fn().mockReturnValue(() => Promise.resolve(mockData)),
}));

我知道有一些方法可以使用此处使用的酶进行测试,但我正在尝试了解使用 Jest 进行的模拟以及我做错了什么。

幻灯片p2

jest.spyOn()应该管用。您需要使用act的异步版本来应用已解决的承诺。可以参考官方示例testing-recipes.html#data-fetching

import React from 'react';
import { act, create } from 'react-test-renderer';
import { MyComponent } from './mycomponent';
import myservice from '../services/myservice';
import { ServiceResponse } from '../services/serviceResponse';

const mockData: ServiceResponse[] = [
  { label: 'a', id: 'b' },
  { label: 'f', id: 'g' },
];

describe('mycomponent', () => {
  it('MyComponent returns data', async () => {
    jest.spyOn(myservice, 'GetServiceData').mockResolvedValue(mockData);
    let root;
    await act(async () => {
      root = create(<MyComponent />);
    });
    console.log(root.toJSON());
  });
});

测试结果:

 PASS  examples/69293771/components/mycomponent.test.tsx (7.271 s)
  mycomponent
    ✓ MyComponent returns data (25 ms)

  console.log
    { type: 'div', props: {}, children: [ 'row' ] }

      at examples/69293771/components/mycomponent.test.tsx:19:13

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.755 s, estimated 9 s

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在React应用程序中使用Jest模拟导入/模块

在React Redux应用程序中使用Jest模拟浅呈现的承诺

如何使用 Jest 模拟服务的属性(而不是函数/方法)

在使用Jest时模拟被测试者调用的服务方法

使用Jest在React Native中模拟孩子

在React.js中使用Jest模拟Bing Maps API

在React中使用jest.fn()模拟获取

如何使用Jest模拟模拟模块的方法?

使用Jest的Nestjs模拟服务构造函数

如何在 Node JS Azure 中使用 Expo 部署 React Native Web 应用程序 - 应用服务

React 中的 Jest 模块模拟

用Jest模拟React组件

React Native:Jest模拟平台

如何在Jest中使用JavaScript模拟服务?

在 React 应用程序中使用 ActiveMQ

使用Jest测试react-native应用程序时未定义XMLHttpRequest

在使用 Jest 测试 React 应用程序时处理发布请求和令牌

如何使用 JEST 在方法中模拟方法?

使用Create React App配置Jest在测试之间重置模拟

使用 React 和 Jest,如何模拟需要等待的 Promise?

如何使用 React 和 Jest 模拟 onPast 事件?

如何使用 Jest Javascript React Native 模拟“替换”功能?

使用Jest和React模拟非默认功能

使用Jest模拟带有道具的React组件

在React Native + Typescript应用程序上运行Jest时出错(Jest遇到意外令牌)

如何使用 Jest 模拟本机 javascript 方法?

愚蠢的问题:关于在React应用程序中使用后端服务器的REST API的担忧

在应用程序中使用服务

如何在 React 中使用 Jest 模拟 window.location.href?