我正在尝试模拟axios调用以进行无端开发-React。我已经对大多数功能进行了单元测试,所以我确定它们可以正常工作,我希望实现一个假后端来演示完整的应用程序。
我的登录(thunk)功能如下:
import React from "react";
import redux from "redux";
import axios from "axios";
import { AsyncStorage as storage } from "react-native";
import { JWTTOKEN, loginUrl } from "../config";
import { loginError, loginLoading, loginSuccess } from "../redux";
export const login = (user, password, api = loginUrl) => {
console.log("login function");
return dispatch => {
dispatch(loginLoading(true));
return axios
.post(loginUrl, {
user: {
user: user,
password: password
}
})
.then(response => {
console.log("reponse: ", response);
storage.setItem(JWTTOKEN, response.data.JWTTOKEN);
dispatch(loginLoading(false));
dispatch(loginSuccess(response.data.user));
return response;
})
.catch(error => {
console.log("error: ", error);
dispatch(loginError(true));
});
};
};
这是我在调用函数的地方(并尝试模拟后端):
import React from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import { login } from "../services";
//FAKE BACKEND
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { JWTTOKEN, loginUrl } from "../config";
const mockApi = new MockAdapter(axios);
/////////////
export class SignInScreen extends React.Component {
state = {
user: "",
password: ""
};
static navigationOptions = {
title: "Please sign in"
};
render() {
console.log("sign in screen");
return (
<View>
<Text>hello</Text>
<Button title="Sign in!" onPress={this._signInAsync} />
</View>
);
}
_signInAsync = async () => {
//FAKE BACKEND
mockApi.onPost(loginUrl).reply(config => {
console.log("fake login post");
return [200, { JWTTOKEN: "tester token", user: "test" }];
});
/////////////
const { user, password } = this.props;
await login(user, password);
this.props.navigation.navigate("AuthLoading");
};
}
});
这种方法在单元测试中有效,例如:
it("sets JWT on status 200", async () => {
expect.assertions(1);
mockApi.onPost(loginUrl).reply(config => {
return [200, { JWTTOKEN: token }];
});
await store.dispatch(login(user, password));
const test = await storage.getItem(JWTTOKEN);
expect(test).toEqual(token);
});
但是我没有达到axios调用的响应或错误响应?任何建议表示赞赏