【发布时间】:2018-08-07 09:31:24
【问题描述】:
我正在尝试测试一个 React 组件,其中包含对 api 库的调用,因此返回了一个承诺。
api 库如下所示:(utils/api.js)
import axios from "axios";
import Q from "q";
export default {
createTrip(trip) {
return Q.when(axios.post("/trips/", trip));
}
}
我已经模拟如下:(utils/__mocks__/api.js)
export default {
createTrip(trip) {
return new Promise((resolve, reject) => {
let response = {status: 201, data: trip};
resolve(response)
})
}
}
我正在测试的功能是:
create() {
api.createTrip(this.state.trip).then(response => {
if (response.status === 201) {
this.setState({trip: {}, errors: []});
this.props.onTripCreate(response.data);
} else if (response.status === 400) {
this.setState({errors: response.data})
}
});
}
测试是:
jest.mock('utils/api.js');
test('succesful trip create calls onTripCreate prop', () => {
const trip = {'name': faker.random.word()};
const spy = jest.fn();
const container = shallow(<TripCreateContainer onTripCreate={spy}/>);
container.setState({'trip': trip});
container.instance().create();
expect(spy).toHaveBeenCalledWith(trip);
expect(container.state('trip')).toEqual({});
expect(container.state('errors')).toEqual([]);
});
我相信这应该可行,但测试结果是:
succesful trip create calls onTripCreate prop
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
[{"name": "copy"}]
But it was not called.
at Object.test (src/Trips/__tests__/Containers/TripCreateContainer.jsx:74:21)
at new Promise (<anonymous>)
at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
at <anonymous>
我不确定如何解决此测试,如果有人可以提供帮助,我将不胜感激?
【问题讨论】:
-
您的测试中的
trip对象似乎只有name属性。您需要传递response和response.status属性,因为它是从您的 Promise 解决的,并且您正在逻辑中检查它的值 -
我已经编辑了代码,但仍然得到同样的错误@t3__rry
-
好的,您也可以编辑您的问题
-
我已经这样做了,我已经更改了模拟api.js文件@t3__rry
标签: javascript reactjs jestjs es6-promise enzyme