How to enter transaction callback in typeorm? - unit-testing

I'm kind of new in unit testing and trying to make some test with typeorm.
The code I've is this:
public executeTransaction(querys: IQueryTransaction[]) {
return getManager().transaction(async transactionalManager => {
for (const query of querys) {
await transactionalManager.query(query[0], query[1]);
}
});
}
I need to enter the transaction callBack but can't figured out how to do it. I tried to mock getManager and transaction playing with it, but with no results.
I'm using jest, typeorm and nest.
Someone knows how to do this?.
EDIT: Connecting to the database is not an option

I think you should try something like this...
return await getManager().transaction(async transactionalManager => {
for (const query of querys) {
await transactionalManager.query(query[0], query[1]);
}
});
OR
import {getManager} from "typeorm";
await getManager().transaction(async transactionalManager => {
await transactionalManager.save(users);
await transactionalManager.save(photos);
});
OR
#Controller("/user")
export class UserController {
constructor(
private userService: UserService,
) {}
#Post("/")
#Transaction()
async createNewUser(#Body() body: UserDTO) {
return await this.userService.createNewUser(body);
}
}

you can use Istambul to simplify your life.
/* istanbul ignore next */

Related

Svelte with Apollo GraphQl - Mutation is not getting triggered

I'm working with my own api and I can see it work if I use #urql/svelte but since we're using Apollo with React on most of our projects, I would like to see the differences between frameworks using the same dependency.
My lib/client.js looks like this:
import { ApolloClient, HttpLink, InMemoryCache } from '#apollo/client/core';
function createApolloClient() {
const httpLink = new HttpLink({
uri: 'MY_API'
});
const cache = new InMemoryCache();
const client = new ApolloClient({
httpLink,
cache
});
return client;
}
const client = new createApolloClient();
export default client;
My index.svelte is looking like this
<script>
import { setClient, mutation } from 'svelte-apollo';
import { gql } from '#apollo/client/core';
import { browser } from '$app/env';
import { onMount } from 'svelte';
import client from '../lib/client';
const email = 'AN_EMAIL';
const password = 'A_PASSWORD';
let userName;
let isLoggedIn = false;
setClient(client);
const SIGN_IN = gql`
mutation ($email: String!, $password: String!) {
userSignIn(email: $email, password: $password) {
email
id
isEnabled
name
surname
userType
}
}
`;
const signInMutation = mutation(SIGN_IN);
async function signInAction() {
await try {
signInMutation({ variables: { email, password } }).then((result) => console.log(result));
} catch (error) {
console.log(error);
}
}
const isUserLoggedIn = () => {
if (browser && localStorage.getItem('isLoggedIn') && localStorage.getItem('userName')) {
isLoggedIn = true;
userName = localStorage.getItem('userName');
}
};
onMount(() => {
isUserLoggedIn();
});
</script>
<button on:click={signInAction}>Trigger</button>
{#if isLoggedIn}
<h1>Welcome {userName}</h1>
{/if}
I honestly can't figure out what I'm missing with the Apollo setup.
I have no errors on my console and my network doesn't show anything when I click the button. The UI seems to work fine with the urql setup.
Could someone point me in the right direction? Thank you!
You have an issue in your client setup:
// ...
// const client = new createApolloClient(); // wrong use of 'new' keyword, createApolloClient() is a regular function, not a class constructor!
const client = createApolloClient();
// ...
As stated in my comment, you also have an issue in your signInAction function definition. You need to settle for one syntax:
// async/await
async function signInAction() {
try {
const result = await signInMutation({ variables: { email, password } });
console.log(result);
} catch (error) {
console.log(error);
}
}
// then/catch
function signInAction() {
signInMutation({ variables: { email, password } })
.then((result) => console.log(result))
.catch((error) => console.log(error));
}
Off-topic and opinionated: svelte-apollo radically differs from the react apollo client, is not an 'official' apollo client, and has not been updated for the past year+. You will be much better off going back to #urql/svelte.

Jest mock twilio - how to?

I have been using Jest to do my unit tests with node.
I am used to mocking the first level of the modules/functions, but on the challenge to mock Twilio, I am not having so much luck.
I am using the twilio method: client.messages.create, so here I have the twilio client from the constructor require('twilio')(account sid, token), and the first layer is from the object/method(?) messages, and last the third level create, and it's this last guy that I am trying to mock.
I was trying something like this:
jest.mock('twilio', () => {
const mKnex = {
messages: jest.fn(),
};
return jest.fn(mKnex);
});
However, I am not able to mock the client resolved value, where I get client.message.create is not a function.
If I try the above mock plus this client.messages.create.mockReturnValueOnce({sid: "FOO", status: "foo"); I get that cannot read the property create from undefined(messages).
Any tip, post, docs that could give me some luck on this?
Thanks
The solution for this is:
Create a file for Twilio client:
// sms.client.ts
import { Twilio } from 'twilio';
const smsClient = new Twilio(
'TWILIO-ACCOUNT-SID',
'TWILIO-TOKEN'
);
export { smsClient };
Then, your service file should look like this:
// sms.service.ts
import { smsClient } from './sms.client';
class SMSService {
async sendMessage(phoneNumber: string, message: string): Promise<string> {
const result = await smsClient.messages.create({
from: '(555) 555-5555',
to: phoneNumber,
body: message,
});
if (result.status === 'failed') {
throw new Error(`Failed to send sms message. Error Code: ${result.errorCode} / Error Message: ${result.errorMessage}`);
}
return result.sid;
}
}
export const smsService = new SMSService();
Last but not least, your spec/test file needs to mock the client file. E.g.
// sms.service.spec.ts
import { MessageInstance, MessageListInstance } from 'twilio/lib/rest/api/v2010/account/message';
import { smsClient } from './sms.client';
import { smsService } from './sms.service';
// mock the client file
jest.mock('./sms.client');
// fixture
const smsMessageResultMock: Partial<MessageInstance> = {
status: 'sent',
sid: 'AC-lorem-ipsum',
errorCode: undefined,
errorMessage: undefined,
};
describe('SMS Service', () => {
beforeEach(() => {
// stubs
const message: Partial<MessageListInstance> = {
create: jest.fn().mockResolvedValue({ ...smsMessageResultMock })
};
smsClient['messages'] = message as MessageListInstance;
});
it('Should throw error if response message fails', async () => {
// stubs
const smsMessageMock = {
...smsMessageResultMock,
status: 'failed',
errorCode: 123,
errorMessage: 'lorem-ipsum'
};
smsClient.messages.create = jest.fn().mockResolvedValue({ ...smsMessageMock });
await expect(
smsService.sendMessage('(555) 555-5555', 'lorem-ipsum')
).rejects.toThrowError(`Failed to send sms message. Error Code: ${smsMessageMock.errorCode} / Error Message: ${smsMessageMock.errorMessage}`);
});
describe('Send Message', () => {
it('Should succeed when posting the message', async () => {
const resultPromise = smsService.sendMessage('(555) 555-5555', 'lorem-ipsum');
await expect(resultPromise).resolves.not.toThrowError(Error);
expect(await resultPromise).toEqual(smsMessageResultMock.sid);
});
});
});
I've found a solution. It's still calling the endpoint, but for each twilio account, you get a test SID and Token, I used this one so it does not send a sms when testing with this:
if (process.env.NODE_ENV !== 'test') {
client = require('twilio')(accountSid, authToken)
listener = app.listen(3010, function(){
console.log('Ready on port %d', listener.address().port)
})
}else{
client = require('twilio')(testSid, testToken)
}

Trying to mock response body from a fetch for a unit test

I'm pretty new to sinon and proxyquire and I think I've read all the answers here on SO but I'm still not finding out what I need. Anyway, here's a sanitized version of my code.
const fetch = require('node-fetch');
async function deleteID(id, endpoint) {
try {
let url = `${endpoint}/delete/${id}`;
let res = await fetch(url, { method: 'DELETE' });
res = await res.json(); // <---- THIS FAILS WHEN fetch IS MOCKED
// do stuff with res
} catch (err) {
logger.error(`Error: ${JSON.stringify(err)}`);
}
}
It's pretty simple, it uses node-fetch to hit a url and then does stuff if the request succeeds or fails. Here's my test, lets setup the mocking for fetch:
const proxyquire = require('proxyquire').noCallThru();
const sinon = require('sinon');
beforeEach((done) => {
const validResponse = {
status: 200,
data: 'hello, world\n'
};
deleteProxy = proxyquire('./delete', {
'node-fetch': sinon.stub().returns(Promise.resolve(JSON.stringify(validResponse)))
});
});
So the fetch call now returns validResponse instead of hitting the server. And here's my test:
it.only('should delete', async () => {
try {
deleteProxy.deleteID('id', 'endpoint');
} catch (err) {
expect(err.message).to.have.lengthOf.at.least(0);
}
});
This fails since res is just an object with status and data, it is not a proper Response that has a Body etc... The rest of our code uses node-mocks-http but all of the tests using that module hit the url directly, not indirectly, via fetch, like I'm doing above.
How do I either create a mocked Response to fit into the above test or is there a different approach I should be using?
By looking at the code and my experience with sinon I would say as this is not an actual HTTP response so you have to mock json() as well.
In beforeEach method:
const body = {
status: 200,
data: 'hello, world\n'
};
var validResponse = { json: () => { return body } };
deleteProxy = proxyquire('./delete', {
'node-fetch': sinon.stub().returns(Promise.resolve(validResponse))
});
try with out JSON.stringify()
Let me know if it doesn't work.

Vue with jest - Test with asynchronous call

How to make my test wait for the result of my api?
I'm using vue and jest to test my components.
I want to test the method that writes a client to my database. In my component I have the following method:
methods: {
onSubmitClient(){
axios.post(`urlApi`, this.dados).then(res => {
return res;
})
}
}
in my test
describe('login.vue', () => {
let wrapper
beforeAll(()=>{
wrapper = mount(client, {
stubs: ['router-link'],
store,
data() {
return {
dados: {
name: 'tes name',
city: 'test city'
},
};
}
})
})
it('store client', () => {
res = wrapper.vm.onSubmitLogin()
console.log(res);
})
})
My test does not wait for the API call to complete. I need to wait for the API call to know if the test worked. How can I make my test wait for API return?
There are several issues in your code.
First, you cannot return from an async call. Instead, you should be probably setting up some data in your onSubmitClient, and returning the whole axioscall, which is a Promise. for instance:
onSubmitClient(){
return axios.post(`urlApi`, this.dados).then(res => {
this.result = res;
return res;
})
}
I assume the method here is storing a result from the server. Maybe you don't want that; it is just an example. I'll come back to it later.
Ok, so now, you could call onSubmitClient in your wrapper and see if this.result is already set. As you already know, this does not work straightforward.
In order for a jest test to wait for asynchronous code, you need either to provide a done callback function or return a promise. I'll show an example with the former:
it('store client', (done) => {
wrapper.vm.onSubmitLogin().then((res) => {
expect(wrapper.vm.dados).toEqual(res);
done();
})
});
Now this code should just work, but still there is an issue with it, as #jonsharpe says in a comment.
You usually don't want to perform real network requests in unitary tests because they are slow and unrealiable. Also, unitary tests are meant to test components in isolation, and here we are testing not only that our component sets this.result properly when the request is made. We are also testing that there is a webserver up and running that is actually working.
So, what I would do in this scenario to test that single piece of functionality, is to extract the request to another method, mock it with vue-test-utils and jest.fn, and then assert that onSubmitClient does its work:
The component:
export default {
data() {
return {
http: axios,
...
},
methods: {
onSubmitClient(){
this.http.post(`urlApi`, this.dados).then(res => {
this.result = res;
})
}
}
}
}
The test:
it('store client', (done) => {
const fakeResponse = {foo: 'bar'};
var post = jest.fn();
var http : {
post,
};
var wrapper = mount(client, {
stubs: ['router-link'],
store,
data() {
return {
dados: {
name: 'tes name',
city: 'test city'
},
http, //now, the component under test will user a mock to perform the http post request.
}
}
});
wrapper.vm.onSubmitLogin().then( () => {
expect(post).toHaveBeenCalled();
expect(wrapper.vm.result).toEqual(fakeResponse);
done();
})
});
Now, your test asserts two things:
post gets called.
this.result is set as it should be.
If you don't want to store anything in your component from the server, just drop the second assertion and the this.result = res line in the method.
So basically this covers why your test is not waiting for the async request and some issues in your code. There are still some things to consider (f.i. I think a global wrapper is bad idea, and I would always prefer shallowMount over mount when testing components behavior), but this answer should help you a lot.
PS: didn't test the code, so maybe I messed up something. If the thing just doesn't work, look for syntax errors or similar issues.

Testing component logic with Angular2 TestComponentBuilder

There are a lot of different approaches to unit test your angular application you can find at the moment. A lot are already outdated and basically there's no real documentation at this point. So im really not sure which approach to use.
It seems a good approach at the moment is to use TestComponentBuilder, but i have some trouble to test parts of my code especially if a function on my component uses an injected service which returns an observable.
For example a basic Login Component with a Authentication Service (which uses a BackendService for the requests).
I leave out the templates here, because i don't want to test them with UnitTests (as far as i understood, TestComponentBuilder is pretty useful for this, but i just want to use a common approach for all my unit tests, and the it seems that TestComponentBuilder is supposed to handle every testable aspect, please correct me if i'm wrong here)
So i got my LoginComponent:
export class LoginComponent {
user:User;
isLoggingIn:boolean;
errorMessage:string;
username:string;
password:string;
constructor(private _authService:AuthService, private _router:Router) {
this._authService.isLoggedIn().subscribe(isLoggedIn => {
if(isLoggedIn) {
this._router.navigateByUrl('/anotherView');
}
});
}
login():any {
this.errorMessage = null;
this.isLoggingIn = true;
this._authService.login(this.username, this.password)
.subscribe(
user => {
this.user = user;
setTimeout(() => {
this._router.navigateByUrl('/anotherView');
}, 2000);
},
errorMessage => {
this.password = '';
this.errorMessage = errorMessage;
this.isLoggingIn = false;
}
);
}
}
My AuthService:
#Injectable()
export class AuthService {
private _user:User;
private _urls:any = {
...
};
constructor( private _backendService:BackendService,
#Inject(APP_CONFIG) private _config:Config,
private _localStorage:LocalstorageService,
private _router:Router) {
this._user = _localStorage.get(LOCALSTORAGE_KEYS.CURRENT_USER);
}
get user():User {
return this._user || this._localStorage.get(LOCALSTORAGE_KEYS.CURRENT_USER);
}
set user(user:User) {
this._user = user;
if (user) {
this._localStorage.set(LOCALSTORAGE_KEYS.CURRENT_USER, user);
} else {
this._localStorage.remove(LOCALSTORAGE_KEYS.CURRENT_USER);
}
}
isLoggedIn (): Observable<boolean> {
return this._backendService.get(this._config.apiUrl + this._urls.isLoggedIn)
.map(response => {
return !(!response || !response.IsUserAuthenticated);
});
}
login (username:string, password:string): Observable<User> {
let body = JSON.stringify({username, password});
return this._backendService.post(this._config.apiUrl + this._urls.login, body)
.map(() => {
this.user = new User(username);
return this.user;
});
}
logout ():Observable<any> {
return this._backendService.get(this._config.apiUrl + this._urls.logout)
.map(() => {
this.user = null;
this._router.navigateByUrl('/login');
return true;
});
}
}
and finally my BackendService:
#Injectable()
export class BackendService {
_lastErrorCode:number;
private _errorCodes = {
...
};
constructor( private _http:Http, private _router:Router) {
}
post(url:string, body:any):Observable<any> {
let options = new RequestOptions();
this._lastErrorCode = 0;
return this._http.post(url, body, options)
.map((response:any) => {
...
return body.Data;
})
.catch(this._handleError);
}
...
private _handleError(error:any) {
...
let errMsg = error.message || 'Server error';
return Observable.throw(errMsg);
}
}
Now i want to test the basic logic of logging in, one time it should fail and i expect an error message (which is thrown by my BackendService in its handleError function) and in another test it should login and set my User-object
This is my current approach for my Login.component.spec:
Updated: added fakeAsync like suggested in Günters answer.
export function main() {
describe('Login', () => {
beforeEachProviders(() => [
ROUTER_FAKE_PROVIDERS
]);
it('should try and fail logging in',
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
tcb.createAsync(TestComponent)
.then((fixture: any) => {
tick();
fixture.detectChanges();
let loginInstance = fixture.debugElement.children[0].componentInstance;
expect(loginInstance.errorMessage).toBeUndefined();
loginInstance.login();
tick();
fixture.detectChanges();
expect(loginInstance.isLoggingIn).toBe(true);
fixture.detectChanges();
expect(loginInstance.isLoggingIn).toBe(false);
expect(loginInstance.errorMessage.length).toBeGreaterThan(0);
});
})));
it('should log in',
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
tcb.createAsync(TestComponent)
.then((fixture: any) => {
tick();
fixture.detectChanges();
let loginInstance = fixture.debugElement.children[0].componentInstance;
loginInstance.username = 'abc';
loginInstance.password = '123';
loginInstance.login();
tick();
fixture.detectChanges();
expect(loginInstance.isLoggingIn).toBe(true);
expect(loginInstance.user).toEqual(jasmine.any(User));
});
})));
});
}
#Component({
selector: 'test-cmp',
template: `<my-login></my-login>`,
directives: [LoginComponent],
providers: [
HTTP_PROVIDERS,
provide(APP_CONFIG, {useValue: CONFIG}),
LocalstorageService,
BackendService,
AuthService,
BaseRequestOptions,
MockBackend,
provide(Http, {
useFactory: function(backend:ConnectionBackend, defaultOptions:BaseRequestOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
})
]
})
class TestComponent {
}
There are several issues with this test.
ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'length' of null' I get this for the test of `loginInstance.errorMessage.length
Expected true to be false. in the first test after i called login
Expected undefined to equal <jasmine.any(User)>. in the second test after it should have logged in.
Any hints how to solve this? Am i using a wrong approach here?
Any help would be really appreciated (and im sorry for the wall of text / code ;) )
As you can't know when this._authService.login(this.username, this.password).subscribe( ... ) is actually called you can't just continue the test synchronically and assume the subscribe callback has happened. In fact it can't yet have happened because sync code (your test) is executed to the end first.
You can add artificial delays (ugly and flaky)
You can provide observables or promises in your component that emit/resolve when something you want to test is actually done (ugly because test code added to production code)
I guess the best option is using fakeAsync which provides more control about async execution during tests (I haven't used it myself)
As far as I know there will come support in Angular tests using zone, to wait for the async queue to become empty before the test continues (I don't know details about this neither).