How to set the MockBackend status code? - unit-testing

For an HTTP test I've got these providers ..
providers: [
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (pBackend: MockBackend, pOptions: BaseRequestOptions) => {
return new Http(pBackend, pOptions);
},
deps: [MockBackend, BaseRequestOptions]
}
]
I can mock a success response ..
let backend = injector.get(MockBackend);
backend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: {mydata:'somedata'}
}
)));
});
and an error response ..
let backend = injector.get(MockBackend);
backend.connections.subscribe(
(connection: MockConnection) => {
connection.mockError(new Error('error'));
});
but please, how do i mock a non 200 response. E.G. how do I respond with HTTP status code 418 for example?
Thanks

Just add a status property to the ResponseOptions
new ResponseOptions({
body: {mydata:'somedata'},
status: 418
})
See the docs for other properties

Related

Auth.federatedSignIn({provider: "Facebook"}) in react native returns [ERROR] OAuth - Error handling auth response. [Error: invalid_client]

I am trying to configure a Social Sign In for Facebook in my react native mobile app using Cognito's hosted UI. My intention is to have any user that signs in with Facebook to have an enabled user in my Cognito User Pool.
However, when I click my "Login with Facebook" button and redirected to Cognito/Facebook's auth flow, it closes the embedded browser immediately and shows the following error in the logs:
[ERROR] 19:02.561 OAuth - Error handling auth response. [Error: invalid_client]
I have a manually configured aws backend with the following configuration:
export default awsConfig = {
Auth: {
"aws_project_region": "us-west-2",
identityPoolId: 'us-east-1:xxxxxx',
region: 'us-east-1',
userPoolId: 'us-east-xxxxx',
userPoolWebClientId: 'xxxxxx',
mandatorySignIn: false,
oauth: {
domain: "myapp.auth.us-east-1.amazoncognito.com",
scope: [
"email",
"openid",
],
redirectSignIn: "myapp://",
redirectSignOut: "myapp://",
responseType: "code",
urlOpener
},
federationTarget: "COGNITO_USER_POOLS"
}
}
This is my Facebook Login configuration:
And here is my react native code:
import React, { Component } from 'react';
import Amplify, { Auth, Hub } from 'aws-amplify';
import awsConfig from './aws-custom-exports';
const configObj = Amplify.configure(awsConfig);
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Button
} from 'react-native';
class App extends Component {
state = {
user: null,
customState: null
};
componentDidMount() {
Hub.listen("auth", ({ payload: { event, data } }) => {
switch (event) {
case "signIn":
this.setState({ user: data });
console.log("Sign in event recorded.")
break;
case "signOut":
this.setState({ user: null });
break;
case "customOAuthState":
this.setState({ customState: data });
console.log("Custom OAuth event recorded.")
default:
console.log("Other auth event: ", data)
}
})
Auth.currentAuthenticatedUser()
.then(user => this.setState({ user }))
.catch(() => console.log("Not signed in"));
}
render() {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<View style={styles.body}>
<Button onPress={() => {
Auth.federatedSignIn({provider: "Facebook"})
.then(data => {
console.log(data)
})
.catch(err => {
console.error(err)
})
}} title="Login with Facebook" />
</View>
</ScrollView>
</SafeAreaView>
</>
);
}
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
body: {
backgroundColor: Colors.white,
}
});
export default App;
My Info.plist file has the CFBundleURLSchemes set to myapp and have added the RTCLinking code snippets to my AppDelegate.m

How to connect deployed Heroku app to Django server

I have deployed heroku app that is based on Django, and React but whenever i want to login into the deployed app i'm getting an error
POST http://localhost:8000/api/auth/jwt/create/ net::ERR_CONNECTION_REFUSED
Initially i had my react login api as http://localhost:8000/api/auth/jwt/create/ then changed it to http://127.0.0.1:8000/api/auth/jwt/create/ but i keep getting the same error.
login file in react
// LOGIN
export const login = (email, password) => async (dispatch) => {
const body = JSON.stringify({ email, password });
await axios
.post("http://127.0.0.1:8000/api/auth/jwt/create/", body)
.then((res) => {
try {
dispatch({
type: LOGIN_SUCCESS,
payload: res.data,
});
dispatch(createMessage({ login: "Login Successful" }));
} catch (error) {
console.log(res, error);
}
})
.catch((err) => {
console.log(err);
dispatch({
type: LOGIN_FAIL,
});
});
}

403 forbidden error when uploading to S3 bucket

I'm pretty new with AWS but im fairly certain I had my IAM user set up properly... are there any other permissions i need to add other than AmazonS3FullAccess? the name implies that it should be enough... either its a permissions issue or I messed up somewhere with my code.
I was trying to follow along with the guide at https://devcenter.heroku.com/articles/s3-upload-node. any help would be appreciated. :)
Here is my relevant code:
//server side code
router.get('/sign-s3', (req, res) => {
const s3 = new aws.S3();
const { fileName, fileType } = req.query;
s3.getSignedUrl('putObject', {
Bucket: S3BUCKET,
Key: fileName,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
}, (err, data) => {
if (err) {
console.log(err);
res.status(500).json(err)
}
res.json({
signedRequest: data,
url: `https://${S3BUCKET}.s3.amazonaws.com/${fileName}`
});
});
});
//client side code
const onChangeHandler = (e) => {
const file = e.target.files[0];
axios
.get(`/api/bucket/sign-s3?fileName=${file.name}&fileType=${file.type}`)
.then(signedResponse => {
axios
.put(signedResponse.data.signedRequest,file, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
console.log("upload successful");
props.addImages([signedResponse.data.url]);
})
.catch(error => console.error(error));
})
.catch(error => console.error(error));
}
and a screenshot of my error:
UPDATE:
Removing the line ACL: 'public-read' from my sign route allows the upload to go through but then nobody can access the images. :P based on johns comments down below i assumed it was some kind of header issue so i added 'x-amz-acl': 'public-read' header to my put request on the client side but its still giving me the same issue of an invalid signature
I was receiving same error with an IAM user with "AmazonS3FullAccess". What worked for me was adding this CORS configuration
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT",
"POST"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]

I have an app with react as frontend and django rest framework as backend, i use axios to send my response, but the data is empty

I have an app with react and Django rest framework. I use Django allauth for login and registration. when I want to log in, everything is ok, and the response is 201 but the data is empty and I don't get token. I send this request with the postman and I get the token. what should i do?
React Request:
axios({
method: 'post',
url: 'http://localhost:8000/rest-auth/login/',
data: {
username: 'admin',
email: '',
password: 'admin123456'
},
headers: { 'content-type': 'application/json' }
})
.then(response => {
console.log(response.data.key);
})
.catch(error => {
console.log(error);
});
the response is:
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
postman request: http://localhost:8000/rest-auth/login/
{
"username": "mahtab",
"email": "",
"password": "mahtab23"
}
postman response:
{
"key": "f75b9f54848a94ac04f455321118aff5d5a7e6f8"
}

angular2 testing: add latency to mock http backend

I have a service that gets data from two different backends (database over http request and live data over socket.io) and then publishes this data as a single stream. When testing this service, I would like to be able to control the delay of the mock http service, so that I can play through different kinds of racing conditions. Currently I'm doing this:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
DataService,
{
provide: IoService,
useClass: MockIoService
},
{
provide: Http,
useFactory: (mockBackend, options) => {
return new Http(mockBackend, options);
},
deps: [MockBackend, BaseRequestOptions]
},
MockBackend,
BaseRequestOptions
]
});
});
it('should get data from http backend', async(inject([DataService, MockBackend, IoService], (service: DataService, mockBackend, ioService) => {
const mockResponse = {
data: [
{ id: 0, text: 'httpData', start: 0, stop: 1 }
]
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponse)
})));
});
service.subscribe('test').subscribe((data) => {
expect(data.text).toBe('httpData');
});
})));
This works but again, I would like to be able to define a delay for the MockBackend so that the response comes after a fixed number of seconds. Is that possible and if yes, how?