gpt4 book ai didi

reactjs - 如何使用 Jest 测试异步组件?

转载 作者:行者123 更新时间:2023-11-28 19:59:51 28 4
gpt4 key购买 nike

谁能告诉我如何在安装调用 componendDidMount() 的组件时 Jest 等待一个模拟的 promise 来解决? ?

class Something extends React.Component {
state = {
res: null,
};

componentDidMount() {
API.get().then(res => this.setState({ res }));
}

render() {
if (!!this.state.res) return
return <span>user: ${this.state.res.user}</span>;
}
}

API.get()在我的 Jest 测试中被 mock

data = [
'user': 1,
'name': 'bob'
];

function mockPromiseResolution(response) {
return new Promise((resolve, reject) => {
process.nextTick(
resolve(response)
);
});
}

const API = {
get: () => mockPromiseResolution(data),
};

然后是我的测试文件:

import { API } from 'api';
import { API as mockAPI } from '__mocks/api';

API.get = jest.fn().mockImplementation(mockAPI.get);

describe('Something Component', () => {
it('renders after data loads', () => {
const wrapper = mount(<Something />);
expect(mountToJson(wrapper)).toMatchSnapshot();
// here is where I dont know how to wait to do the expect until the mock promise does its nextTick and resolves
});
});

问题是我 expect(mountToJson(wrapper))正在返回 null因为 <Something /> 的模拟 api 调用和生命周期方法还没有通过。

最佳答案

Jest 有伪造的模拟 time travelling ,要在您的情况下使用它,我想您可以按以下样式更改代码:

import { API } from 'api';
import { API as mockAPI } from '__mocks/api';

API.get = jest.fn().mockImplementation(mockAPI.get);

jest.useFakeTimers(); // this statement makes sure you use fake timers

describe('Something Component', () => {
it('renders after data loads', () => {
const wrapper = mount(<Something />);

// skip forward to a certain time
jest.runTimersToTime(1);

expect(mountToJson(wrapper)).toMatchSnapshot();
});
});

除了 jest.runTimersToTime(),您还可以使用 jest.runAllTimers()

关于reactjs - 如何使用 Jest 测试异步组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46718663/

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