我跟随React组件,该组件在父组件中呈现为子组件,并且传递了道具:
<Component
localStorageValue={'test-walue'}
requestDataFunc={getData}
requestUserData={getUserData}
expectedResponseKey={'key'}
dataType={'test}
activePage={'index'}
saveData={this.setData}
/>
所以requestDataFunc是一个传递给组件并在componentDidMount中运行的功能:
componentDidMount() {
requestDataFunc().then(({ data }) => {
const { selectedDataItems } = this.state;
const expectedResponseData = data[expectedResponseKey];
let interimDataArr = [];
expectedResponseData.forEach((item) => {
interimDataArr = [...interimDataArr, {
...item,
active: selectedDataItems.length ? selectedDataItems.some((selectedItemId) => selectedItemId === item.id) : false,
}];
});
}
但是当我运行测试时,我得到了:
TypeError:无法读取未定义的属性'then'
requestDataFunc().then(({ data }) => {
const { selectedDataItems } = this.state;
const expectedResponseData = data[expectedResponseKey];
let interimDataArr = [];
我刚刚开始测试渲染组件:
describe('correct component render', () => {
const defaultProps = {
localStorageValue: 'test-walue',
requestDataFunc: jest.fn(),
requestUserData: jest.fn(),
expectedResponseKey: 'key',
dataType: 'test',
activePage: 'index',
saveData: jest.fn(),
};
const wrapper = shallow(<ComponentName { ...defaultProps } />);
test("render component", () => {
expect(wrapper.length).toEqual(1);
});
});
我想我需要模拟请求和该请求应接收的数据。如何正确执行此操作?
答案 0 :(得分:2)
您是否尝试过如下的模拟承诺:
var mockPromise = new Promise((resolve, reject) => {
resolve(<mock response similar to actual promise response>);
});
describe('correct component render', () => {
const defaultProps = {
localStorageValue: 'test-walue',
requestDataFunc: jest.fn().mockReturnValueOnce(mockPromise),
requestUserData: jest.fn(),
expectedResponseKey: 'key',
dataType: 'test',
activePage: 'index',
saveData: jest.fn(),
};
const wrapper = shallow(<ComponentName { ...defaultProps } />);
test("render component", () => {
expect(wrapper.length).toEqual(1);
});
});
答案 1 :(得分:0)
Axios get
方法返回一个Promise,因此,当您模拟该方法时,还需要返回一个Promise
jest.fn(() => Promise.resolve({}))
有关Jest async mocking的更多信息