gpt4 book ai didi

javascript - 在 React 中测试 API 调用 - 状态未更新

转载 作者:行者123 更新时间:2023-11-28 20:13:26 24 4
gpt4 key购买 nike

我想测试在我的组件中调用 API 后我的状态是否更新。我有一个方法可以说 method1() 并且在该方法中,它调用 fetch 并将状态设置为结果。方法如下:

method1 = () => {
if (this.state.state1 !== "") {
fetch('api')
.then((resp) => resp.json())
.then((data) => {
this.setState({ state2: data });
})
.catch((error) => {
console.log(error);
});
}

在我的测试文件中,我已经使用 fetch-mock 模拟了 API,下面是试图对此进行测试的测试:

it('updates the state after the api call', () => {
const instance = component.instance();
instance.method1();
expect(component.state('state2')).toBe(MOCK_DATA);
});

我的 MOCK_DATA 是在 beforeEach() 中与模拟提取和组件(浅层)一起定义的

当我运行它时,state2 仍处于其初始状态 ([]),但我希望它是一个已填充的数组。

我也尝试使测试异步并使用 await 但我得到了相同的结果。

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

最佳答案

这是一个不使用fetch-mock 的解决方案。您可以自己手动模拟 fetch

index.tsx:

import React, { Component } from 'react';
import fetch from 'node-fetch';

interface ISomeComponentState {
state1: string;
state2: string;
}

export class SomeComponent extends Component<any, ISomeComponentState> {
constructor(props) {
super(props);
this.state = {
state1: 'jest',
state2: ''
};
}

public async method1() {
if (this.state.state1 !== '') {
await fetch('api')
.then(resp => resp.json())
.then(data => {
this.setState({ state2: data });
})
.catch(error => {
console.log(error);
});
}
}

public render() {
return <div>test</div>;
}
}

单元测试,index.spec.tsx:

import React from 'react';
import { SomeComponent } from './';
import { shallow, ShallowWrapper } from 'enzyme';
import fetch from 'node-fetch';

const { Response } = jest.requireActual('node-fetch');

jest.mock('node-fetch');

describe('SomeComponent', () => {
let component: ShallowWrapper;
beforeEach(() => {
component = shallow(<SomeComponent></SomeComponent>);
});

it('snapshot', () => {
expect(component).toMatchSnapshot();
});

it('should not fetch api', async () => {
const mockedState = { state1: '', state2: '' };
component.setState(mockedState);
expect(component.state()).toEqual(mockedState);
await (component.instance() as SomeComponent).method1();
expect(fetch).not.toBeCalled();
expect(component.state()).toEqual(mockedState);
});

it('should fetch api correctly', async () => {
(fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(new Response(JSON.stringify('mocked data')));
expect(component.state()).toEqual({ state1: 'jest', state2: '' });
await (component.instance() as SomeComponent).method1();
expect(fetch).toBeCalledWith('api');
expect(component.state()).toEqual({ state1: 'jest', state2: 'mocked data' });
});

it('will fetch error', async () => {
const mockedError = new Error('some error');
const consoleLogSpyOn = jest.spyOn(console, 'log');
(fetch as jest.MockedFunction<typeof fetch>).mockRejectedValueOnce(mockedError);
await (component.instance() as SomeComponent).method1();
expect(fetch).toBeCalledWith('api');
expect(consoleLogSpyOn).toBeCalledWith(mockedError);
expect(component.state()).toEqual({ state1: 'jest', state2: '' });
});
});

100% 覆盖率的单元测试结果:

 PASS  src/stackoverflow/52899150/index.spec.tsx
SomeComponent
✓ snapshot (20ms)
✓ should not fetch api (5ms)
✓ should fetch api correctly (6ms)
✓ will fetch error (11ms)

console.log node_modules/jest-mock/build/index.js:860
Error: some error
at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/52899150/index.spec.tsx:38:25)
at step (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/52899150/index.spec.tsx:32:23)
at Object.next (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/52899150/index.spec.tsx:13:53)
at /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/52899150/index.spec.tsx:7:71
at new Promise (<anonymous>)
at Object.<anonymous>.__awaiter (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/52899150/index.spec.tsx:3:12)
at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/52899150/index.spec.tsx:37:26)
at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
at resolve (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
at process._tickCallback (internal/process/next_tick.js:68:7)

-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 1 passed, 1 total
Time: 4.697s

这是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/52899150

关于javascript - 在 React 中测试 API 调用 - 状态未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com