Javascript 在React状态下测试API调用-未更新
我想测试我的状态是否在组件中的API调用后更新。我有一个方法,比如说Javascript 在React状态下测试API调用-未更新,javascript,reactjs,testing,jestjs,enzyme,Javascript,Reactjs,Testing,Jestjs,Enzyme,我想测试我的状态是否在组件中的API调用后更新。我有一个方法,比如说method1(),在该方法中,它调用fetch,并将状态设置为结果。 方法如下: method1 = () => { if (this.state.state1 !== "") { fetch('api') .then((resp) => resp.json()) .then((data) => { this.setState({ state2: data }); }) .catc
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_数据
与beforeach()中的模拟回迁和组件(浅层)一起定义。
运行此命令时,state2
仍处于初始状态([]
),但我希望它是一个填充的数组
我还尝试了使测试异步并使用await
,但得到了相同的结果
任何帮助都将不胜感激!谢谢 这是一个不使用
fetch mock
的解决方案。您可以自己手动模拟获取
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>;
}
}
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
某些成分
✓ 快照(20ms)
✓ 不应获取api(5ms)
✓ 应正确获取api(6ms)
✓ 将获取错误(11ms)
console.log node_modules/jest mock/build/index.js:860
错误:一些错误
反对