Are lifecycle components and subscription callback running on separate thread? - amazon-web-services

When as soon as I send a message, all the messages above it get deleted. In case I fetch all messages again from the database, it works.
So the following is my code body where I am making an amplify request everytime a new message is generated:
const ChatRoomScreen = () => {
const [messages, setMessages] = useState([]);
const [myId, setMyId] = useState(null);
const route = useRoute();
const fetchMessages = async () => {
const messagesData = await API.graphql(
graphqlOperation(
messagesByChatRoom, {
chatRoomID: route.params.id,
sortDirection: "DESC",
}
)
)
//console.log("FETCH MESSAGES")
setMessages(messagesData.data.messagesByChatRoom.items);
}
useEffect(() => {
fetchMessages();
}, [])
useEffect(() => {
const getMyId = async () => {
const userInfo = await Auth.currentAuthenticatedUser();
setMyId(userInfo.attributes.sub);
}
getMyId();
}, [])
useEffect(() => {
const subscription = API.graphql(
graphqlOperation(onCreateMessage)
).subscribe({
next: (data) => {
const newMessage = data.value.data.onCreateMessage;
if (newMessage.chatRoomID !== route.params.id) {
//console.log("Message is in another room!")
return;
}
setMessages([newMessage, ...messages]); //This line creates issues
//If I fetch all messages again from database, it works.
}
});
return () => subscription.unsubscribe();
}, [])

Related

Proper way to test type-graphql middleware with jest

Context
I am trying to write a jest test for an authentication middleware for a resolver function. I am attempting to mock an implementation so that the next function is called so that the test passes.
Error
The error I receive is "next is not a function". I can verify that the mocked function is called through expect(isAuth).toHaveBeenCalledTimes(1);, but there is clearly an issue with my mocked implementation. Any help is much appreciated.
Code
//isAuth Middleware
import { MiddlewareFn } from "type-graphql";
import { Context } from "../utils/interfaces/context";
export const isAuth: MiddlewareFn<Context> = ({ context }, next) => {
const loggedInUserId = context.req.session.id;
if (!loggedInUserId) {
throw new Error("Not authenticated!");
}
return next();
};
//transaction.test.ts
jest.mock("../middleware/isAuth", () => {
return {
isAuth: jest.fn((_, next) => next()), //also tried (next) => next() and (next)=>Promise.resolve(next())
};
});
test("should create a txn successfully", async () => {
//ARRANGE
const user = await createUser(orm);
const txn = createTxnOptions();
const txnToBeCreated = { ...txn, userId: user.id };
//ACT
const response = await testClientMutate(
TXN_QUERIES_AND_MUTATIONS.CREATE_TXN,
{
variables: txnToBeCreated,
}
);
//expect(isAuth).toHaveBeenCalledTimes(1); passes so it's getting called
console.log(response);
const newlyCreatedTxn: Transaction = (response.data as any)
?.createTransaction;
//ASSERT
const dbTxn = await em.findOne(Transaction, {
id: newlyCreatedTxn.id,
});
expect(newlyCreatedTxn.id).toBe(dbTxn?.id);
});
//transaction.resolver.ts
import { Transaction } from "../entities/Transaction";
import {
Arg,
Ctx,
Mutation,
Query,
Resolver,
UseMiddleware,
} from "type-graphql";
import { Context } from "../utils/interfaces/context";
import { isAuth } from "../middleware/isAuth";
#Mutation(() => Transaction)
#UseMiddleware(isAuth)
async createTransaction(
#Arg("title") title: string,
#Arg("userId") userId: string,
#Ctx() { em }: Context
): Promise<Transaction> {
const transaction = em.create(Transaction, {
title,
user: userId,
});
await em.persistAndFlush(transaction);
return transaction;
}
Replace
jest.mock("../middleware/isAuth", () => {
return {
isAuth: jest.fn((_, next) => next()), //also tried (next) => next() and (next)=>Promise.resolve(next())
};
});
With
jest.mock("../middleware/isAuth", () => {
return {
isAuth: (_, next) => next()
};
});

Jest & AWS.DynamoDB.DocumentClient mocking

I'm trying to mock a call to AWS.DynamoDB.DocumentClient. I tried several solutions I found online, but I cannot get it to work.
This is my best effort so far:
import * as AWS from 'aws-sdk';
import * as dynamoDbUtils from '../../src/utils/dynamo-db.utils';
jest.mock("aws-sdk");
describe('dynamo-db.utils', () => {
describe('updateEntity', () => {
it('Should return', async () => {
AWS.DynamoDB.DocumentClient.prototype.update.mockImplementation((_, cb) => {
cb(null, user);
});
await dynamoDbUtils.updateEntity('tableName', 'id', 2000);
});
});
});
I get error message
Property 'mockImplementation' does not exist on type '(params: UpdateItemInput, callback?: (err: AWSError, data: UpdateItemOutput) => void) => Request<UpdateItemOutput, AWSError>'.ts(2339)
My source file:
import AWS from 'aws-sdk';
let db: AWS.DynamoDB.DocumentClient;
export function init() {
db = new AWS.DynamoDB.DocumentClient({
region: ('region')
});
}
export async function updateEntity(tableName: string, id: string, totalNumberOfCharacters: number): Promise<AWS.DynamoDB.UpdateItemOutput> {
try {
const params = {
TableName: tableName,
Key: { 'id': id },
UpdateExpression: 'set totalNumberOfCharacters = :totalNumberOfCharacters',
ExpressionAttributeValues: {
':totalNumberOfCharacters': totalNumberOfCharacters
},
ReturnValues: 'UPDATED_NEW'
};
const updatedItem = await db.update(params).promise();
return updatedItem;
} catch (err) {
throw err;
}
}
Please advise how can I properly mock the response of AWS.DynamoDB.DocumentClient.update
Have some way to do the that thing (I think so).
This is one of them:
You use AWS.DynamoDB.DocumentClient, then we will mock AWS object to return an object with DocumentClient is mocked object.
jest.mock("aws-sdk", () => {
return {
DynamoDB: {
DocumentClient: jest.fn(),
},
};
});
Now, AWS.DynamoDB.DocumentClient is mocked obj. Usage of update function like update(params).promise() => Call with params, returns an "object" with promise is a function, promise() returns a Promise. Do step by step.
updateMocked = jest.fn();
updatePromiseMocked = jest.fn();
updateMocked.mockReturnValue({
promise: updatePromiseMocked,
});
mocked(AWS.DynamoDB.DocumentClient).mockImplementation(() => {
return { update: updateMocked } as unknown as AWS.DynamoDB.DocumentClient;
});
mocked import from ts-jest/utils, updateMocked to check the update will be call or not, updatePromiseMocked to control result of update function (success/ throw error).
Complete example:
import * as AWS from 'aws-sdk';
import * as dynamoDbUtils from './index';
import { mocked } from 'ts-jest/utils'
jest.mock("aws-sdk", () => {
return {
DynamoDB: {
DocumentClient: jest.fn(),
},
};
});
describe('dynamo-db.utils', () => {
describe('updateEntity', () => {
let updateMocked: jest.Mock;
let updatePromiseMocked: jest.Mock;
beforeEach(() => {
updateMocked = jest.fn();
updatePromiseMocked = jest.fn();
updateMocked.mockReturnValue({
promise: updatePromiseMocked,
});
mocked(AWS.DynamoDB.DocumentClient).mockImplementation(() => {
return { update: updateMocked } as unknown as AWS.DynamoDB.DocumentClient;
});
dynamoDbUtils.init();
});
it('Should request to Dynamodb with correct param and forward result from Dynamodb', async () => {
const totalNumberOfCharacters = 2000;
const id = 'id';
const tableName = 'tableName';
const updatedItem = {};
const params = {
TableName: tableName,
Key: { 'id': id },
UpdateExpression: 'set totalNumberOfCharacters = :totalNumberOfCharacters',
ExpressionAttributeValues: {
':totalNumberOfCharacters': totalNumberOfCharacters
},
ReturnValues: 'UPDATED_NEW'
};
updatePromiseMocked.mockResolvedValue(updatedItem);
const result = await dynamoDbUtils.updateEntity(tableName, id, totalNumberOfCharacters);
expect(result).toEqual(updatedItem);
expect(updateMocked).toHaveBeenCalledWith(params);
});
});
});

how test call back function? VUE/JEST

I no any idea how test updateTotal... if requestAxios is success return callback function updateTotal but how i spy that?
...methods:{
updateAll() {
const updateTotal = (request) => {
this.total = request.data.total
}
this.requestAxios(
'get',
'/api/',
{},
[updateTotal],
)
}
}...
requestAxios:
async requestAxios(
method = 'get',
url = '',
objSend = {},
successFunctions = [],
errorsFunctions = [],
formKey = 'form',
) {
let request = ''
if (method !== 'delete') {
request = await axios[method](url, objSend, this.headerRequestJson)
.then(response => this.responseRequestText(response))
.catch(errors => this.responseRequestText(errors.response));
} else {
request = await axios.delete(url, {
data: objSend,
headers: this.headerRequestJson.headers,
})
.then(response => this.responseRequestText(response))
.catch(errors => this.responseRequestText(errors.response));
}
if (request.status === 'success') {
// success callback fn
successFunctions.forEach((value) => {
value(request, formKey)
})
} else {
// errors callback fn
errorsFunctions.forEach((value) => {
value(request)
})
// adicionar erros nos campos
this.addErrors(request, formKey);
}
},
My attempt:
test('updateTotalFinancial: ', () => {
const update = jest.fn()
const response = {
data: {
total: 100,
},
}
const requestAxios = jest.fn(() => update(response))
const wrapper = shallowMount(ModalUnderwriting, {
store,
localVue,
methods: {
requestAxios,
},
})
wrapper.setData({
total: '0',
})
wrapper.vm.updateTotalFinancial()
first expect success second not, not update data/variabel total
expect(update).toBeCalled()
expect(wrapper.vm.total).toEqual(100)

How to mock functions deeper in the code with jest

Im trying to mock this mail function so I dont send mails everytime I test my code. But the mocking is not working. This code gives me the error: mockImplementation is not a function.
It's the add function that calls sendUserInvitationMail(). The mailer module export looks like this:
module.exports = {
sendUserInvitationMail,
};
this is the test code:
require('dotenv').config();
const { startWithCleanDb } = require('../../../utils/test.helpers');
const { add } = require('../invitation.service');
const { ADMIN_LEVELS, TABLES } = require('../../../constants');
const { AuthorizationError } = require('../../../errors');
const knex = require('../../../../db/connection');
const mailer = require('../../../mailer/index');
jest.mock('../../../mailer/index');
beforeEach(() => startWithCleanDb());
mailer.sendUserInvitationMail.mockImplementation(() => console.log('Mocked mail function called'));
mailer.sendUserInvitationMail();
describe('invitation.service', () => {
describe('add', () => {
it('adds an invitation to the db', async () => {
expect.assertions(2);
const result = await add(
{
email: 'tester#test.be',
badgeNumber: '344d33843',
},
{ currentZoneId: 1 },
ADMIN_LEVELS.ADMINISTRATOR,
);
const invitation = (await knex.select('*').from(TABLES.INVITATIONS))[0];
expect(invitation.id).toEqual(result.id);
expect(invitation.email).toEqual(result.email);
});
});
});
In mailer, sendUserInvitationMail is undefined, so it has no property mockImplementation.
Try:
mailer.sendUserInvitationMail = jest.fn().mockImplementation(() => console.log('Mocked mail function called'));
or
mailer.sendUserInvitationMail = jest.fn(() => console.log('Mocked mail function called'));

How to pass variables to an Apollo Mutation for Graphene?

I'm currently trying to switch from an Apollo server in nodejs to a Graphene server, but I'm having an issue while mutating.
Client side handling
const GeneratedForm = Form.create()(IngredientCategoryForm)
const createCategoryMut = gql`
mutation createCategoryMut($name: String) {
createCategory(name:$name) {
category {
name
}
}
}
`
const createCategoryWithApollo = graphql(createCategoryMut)(GeneratedForm)
export { createCategoryWithApollo as CategoryForm }
I'm mutating this way :
handleSubmit = (e) => {
const {
mutate
} = this.props
e.preventDefault()
this.props.form.validateFields((err, values) => {
if (!err) {
mutate({
variables: { name: 'myName' }
})
.then(({ data }) => {
console.log('got data', data);
}).catch((error) => {
console.log('there was an error sending the query', error);
})
}})
}
server side Mutation
class CreateCategory(graphene.Mutation):
class Arguments:
name = graphene.String()
category = graphene.Field(lambda: Category)
def mutate(self, info, name='toto'):
category = Category(name=name)
return CreateCategory(category=category)