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



我使用React与Typescript和Jest进行单元测试。不我使用酶。

我试图理解Jest的mock功能,特别是确定错误的地方。

我已经使用create-react-app with typescript创建了一个react应用,即

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

问题在于joke . spyon()不模拟数据。我试着使用下面的

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

我知道这里有一些方法可以用酶来测试,但我正试图理解用笑话嘲笑和我做错了什么。

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

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

相关内容

  • 没有找到相关文章