我有一个使用redux-api-middleware
中的RSAA的操作,名为createUser:
export const createUser = values => {
const email = values.get("user_attributes[email]");
const password = values.get("user_attributes[password]");
return dispatch => {
dispatch({
[RSAA]: {
endpoint: `${globalVar.API_URL}/users/`,
method: "POST",
body: values,
types: [
CREATE_USER,
{
type: CREATE_USER_SUCCESS,
payload: (action, state, response) => {
return response.json().then(json => {
dispatch(login(email, password));
dispatch(sendFlashMessage("success", json.message));
return json;
});
}
},
CREATE_USER_FAILURE
]
}
});
};
};
...并且我有一个带有redux-form
的组件,可以使用此操作:
class UserNew extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(values) {
values = { user_attributes: values };
const data = objectToFormData(values);
this.props.actions.createUser(data);
}
render() {
const { handleSubmit, errors } = this.props;
return (
<UserForm
handleSubmit={handleSubmit}
onSubmit={this.onSubmit}
errors={errors}
/>
);
}
}
在我的jest
和enzyme
测试文件中:
it("create new user", done => {
wrapper
.find("#sign-up")
.hostNodes()
.simulate("click");
wrapper
.find('[name="first_name"]')
.hostNodes()
.simulate("change", { target: { value: "User" } });
...
...并填写完表格:
wrapper
.find("form")
.hostNodes()
.simulate("submit");
done();
因此,我想拦截API调用并让它完成这样的操作(调度登录和sendFlashMessage)。
我尝试了moxios
,但没有成功:
moxios.install();
moxios.stubRequest(`${globalVar.API_URL}/users/`, {
status: 200,
response: [{user: {...}, message: "OK"}]
});
我正在尝试使用sinon
来解决此问题
答案 0 :(得分:0)
Sinon没有使用伪造的XHR机制为您立即解决此问题的方法。从您使用的middleware documentation中可以清楚地看出原因:
注意:redux-api-middleware取决于可用的全局Fetch,并且可能需要针对您的运行时环境进行polyfill。
Sinon(或者实际上是其依赖的nise
library)不处理Fetch,仅处理XHR。
您可以使用fake-fetch之类的库,也可以自己简单地存根fetch
。但是,这将涉及相当复杂的存根,包括存根复杂的响应,所以我宁愿这样做:
var fakeFetch = require('fake-fetch');
beforeEach(fakeFetch.install);
afterEach(fakeFetch.restore);
it("should fetch what you need", done => {
fakeFetch.respondWith({"foo": "bar"});
fetch('/my-service', {headers: new Headers({accept: 'application/json'})}).then(data => {
expect(fakeFetch.getUrl()).toEqual('/my-service');
expect(fakeFetch.getMethod()).toEqual('get');
expect(data._bodyText).toEqual('{"foo":"bar"}');
expect(fakeFetch.getRequestHeaders()).toEqual(new Headers({accept: 'application/json'}));
done();
});
});
答案 1 :(得分:0)
示例代码:
import { mount } from "enzyme";
import sinon from "sinon";
beforeAll(() => {
server = sinon.fakeServer.create();
const initialState = {
example: ExampleData,
auth: AuthData
};
wrapper = mount(
<Root initialState={initialState}>
<ExampleContainer />
</Root>
);
});
it("example description", () => {
server.respondWith("POST", "/api/v1/example", [
200,
{ "Content-Type": "application/json" },
'message: "Example message OK"'
]);
server.respond();
expect(wrapper.find(".response").text().to.equal('Example message OK');
})
在上面的代码中,我们可以看到如何使用由酶创建的测试DOM拦截API调用,然后使用sinon模拟API响应。