这是我使用 getAllData 方法调用 API 并将数据设置为状态的组件代码:
class MyComponent extends Component {
state = {
allStatus: []
}
componentDidMount() {
this.getAllData();
}
getAllData = async() => {
let res = await apiCalls(`${Config.masterUrl}/ContentState`, 'GET', {}, `/user-data`, false);
if (res) {
this.setState({allStatus: res});
}
}
}
这是测试用例,首先我调用 componentDidMount 并调用 getAllData 方法,然后使用 moxios 模拟 API,但它不会模拟请求。
describe('Render MyComponent Component', () => {
let wrapper;
beforeEach(() => {
wrapper = setup(initialState);
moxios.install();
});
afterEach(() => {
moxios.uninstall();
})
it("should call getAllData API Success", async(done) => {
const responseData = {
status: 200,
error: null,
data: [Array] // for example
}
await wrapper.instance().componentDidMount();
await wrapper.instance().getAllData()
moxios.wait(function() {
const request = moxios.requests.mostRecent();
request.respondWith(responseData)
expect(wrapper.instance().state.allStatus.length).not.toBe(0)
done()
})
})
})