Accessing result of map/reduce within Ionic2 app using PouchDB - ionic2

I am using PouchDB on an Ionic 2 app that syncs with my CouchDB that is on AWS.
I have created a design document in futon and this works well if I go to http://my-ip-address:5984/wardround_jobs/_design/teams/_view/teams - I can see the JSON that is output by the map/reduce used in my design.
I am now trying to figure out how to access this in my app.
I start with this - it gives me all documents:
return new Promise(resolve => {
this.db.allDocs({
include_docs: true
}).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
});
I can then amend this to get back one specific document:
return new Promise(resolve => {
this.db.get('0448071807c0f37f53e06aab54034a42').then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
});
But if I try and get back my design view using this code then I get back an error:
return new Promise(resolve => {
this.db.get('_design/teams/_view/teams').then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
});
The error is:
CustomPouchError {
status: 404,
name: "not_found",
message: "missing",
error: true,
reason: "missing"
}
How can I access the result from my map/reduce within my app?
EDIT - with the help of Alexis I got this working ...
return new Promise(resolve => {
this.db.get('teams/teams').then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
});

To get the result from any map/reduce design document, you need to use the query() function.

Related

How to mock a #Header request for NestJS unit testing

I am attempting to implement unit testing in NestJS. However, I am new to both NestJS and unit testing in general.
So, what I need to do is to pass a test that gets all projects from a gitlab profile.
#Get()
getProjects(#Headers() headers: any): Observable<Project[]> {
if (!headers.token) {
throw new HttpException('Missing User Token', HttpStatus.BAD_REQUEST);
}
return this.projectsService.listProjects(headers.token);
}
This is the code in the project.controller.ts file. It works well, and returns an observable with the list of projects. However, it requires a header to be sent through the HTTP request(Which is received using the #Headers decorator), as the gitlab is locked behind an authentication that requires a token to be passed through the header of the request.
I have attempted to mock the header to no success, and I was wondering if anyone has any idea how to proceed with the unit testing for that get request.
You don't need anything special here. In your unit test, you just need to pass an object with a token property to your method call.
describe('SomeController', () => {
let controller: SomeController;
let service: jest.Mocked<SomeService>;
beforeAll(async () => {
const modRef = await Test.createTestingModule({
controllers: [SomeController],
providers: [{
provide: SomeService,
useValue: {
method: jest.fn(() => of('value'))
}
}]
}).compile();
controller = modRef.get(SomeController)
service = modRef.get<jest.Mocked<SomeService>>(SomeService)
});
it('getProjects', (done) => {
controller.getProejcts({ token: 'hey look! a token'}).subscribe({
next: (val) => expect(val).toBe('value'),
error: (err) => { throw err; }
complete: () => done()
});
});
})

VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook

I am using jest for unit testing in nuxt js
I have mounted hook like this
async mounted(){
try{
var response = await this.$axios.get("api_url here");
this.result = response.data;
} catch(e){
console.log("Exception: ",e)
}
}
when i do unit test for it my code is . utnit.spec.js
jest.mock("axios", () => ({
get: () => Promise.resolve({ data: [{ val: 1 }] })
}));
import { mount } from '#vue/test-utils';
import file from '../filefile';
import axios from "axios";
describe('file', () => {
test('check comp. working correctly', () => {
var wrapper = mount(file);
afterEach(() => {
wrapper.destroy()
})
})
})
I am getting this warn there and there is no data in the results
Exception: TypeError: Cannot read property 'get' of undefined
at VueComponent.mounted
how do I know what is the problem here, is this I can not access axios in the unit file Is there any specific way to test Axios in mounted hook
The error means that it's this.$axios.get that is not available, not axios.get. The component relies on Axios plugin that is commonly installed in Vue application entry point or Nuxt configuration.
It can be installed for localVue Vue instance in tests, or be supplied directly to the component:
var wrapper = mount(file, { mocks: { $axios: axios } });
Also, the mock will fail if Axios is used as axios() somewhere because default import is expected to be a function:
jest.mock("axios", () => Object.assign(
jest.fn(),
{ get: jest.fn() }
));
axios.get is Jest spy, the implementation is mocked per test depending on the use and isn't limited to hard-coded Promise.resolve({ data: ... }) supplied in the mock.

How to test throw new HttpException in unit test Nest.js

I'm trying to test a service in my Nest.js app. In some of my methods of this service I have some cases where I throw new HttpException depending of the context.
I'm trying to write unit tests of these methods and I don't know how to test cases where I throw HttpException.
I've tried this code:
it('Shound return error for a non existing id provided', async () => {
await expect(service.getUser('false Id')).rejects.toThrow(new HttpException('This user does not exist', 404));
});
But I received:
Expected the function to throw an error matching:
[Error: This user does not exist]
Instead, it threw:
Error: This user does not exist
Does anyone already encounter this use case ?
Duc answer works but if you want some prettier way you might like this,
it('should return null when update', async () => {
await expect(controller.updateById({ id: 'some id' }, {}))
.rejects.toThrowError(NotFoundException);
});
Simply do this:
it('should return null when update', async (done) => {
jest.spyOn(service, 'updateById').mockResolvedValue(null)
try {
await controller.updateById({ id: 'some id' }, {})
} catch (error) {
expect(error).toBeInstanceOf(NotFoundException)
done()
}
})

Unit testing interceptor (axios)

I use axios for the api calls in my react redux app. I added this interceptor to intercept the response for all the api calls and redirect user to login if the status code is 401.
axios.interceptors.response.use((response) => {
if (response.status === 401) {
browserHistory.push('/login');
}
return response;
});
I am unit testing this and asserting on browserHistory spy to get called but I am not sure why my test keeps failing. I'm kind of stuck after loads of tries and am not able to sort out the issue. I am using moxios for mocking response.
Test
let sandbox;
beforeEach(() => {
moxios.install();
sandbox = sinon.sandbox.create();
});
afterEach(() => {
moxios.uninstall();
sandbox.restore();
});
describe('interceptors', () => {
it('should redirect to login if response status code is 401', (done) => {
moxios.withMock(() => {
sandbox.spy(browserHistory, 'push');
axios.get('/test');
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 401,
response: {}
}).then(() => {
expect(browserHistory.push).to.have.been.called; // Fails
done();
}).catch(done);
});
});
});
});
Any sort of resources or guide would be really appreciated. I am pretty sure I am missing something here.

State not changing when unit testing VueJS and VueResource

I'm trying to test a service that I've created that makes an API call with vue-resource. The service should make the call and update the component with the new data, however in my tests it doesn't register the updated value. I'm using the same setup as the vue-cli webpack example and have based my auth service off this repo (which unfortunately doesn't have any tests)
my service:
export default {
login(context, creds){
context.$http.post(LOGIN_URL, creds)
.then((response) => {
//do something else here
}, (response) => {
context.error = response.data.error
}
}
}
my test:
import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)
import Auth from 'src/auth'
describe('Auth', () => {
it('should throw an error on unsuccessful login', (done) => {
//intercept the api call and force an invalid response
Vue.http.interceptors.unshift((request, next) => {
next(request.respondWidth({error: 'some error'}, {status: 401}));
});
const vm = new Vue({
data: {
error: ''
}
}).$mount()
Auth.login(vm, {email: 'test#test.com', pass: 'test'} )
//this always fails
expect(vm.error).to.equal('some error')
//ive also tried:
vm.$nextTick(() => {
expect(vm.error).to.equal('some error')
//done()
});
//undo our interceptor
Vue.http.interceptors.shift()
}
}
When I run the test it fails because it's expecting '' to equal 'some error'.
My suspicions are around the fact that vue-resource is using promises.
After reading through some of the Vue.js tests I found my answer. Instead of using vm.$nextTick I did the following:
setTimeout(function(){
expect(vm.error).to.equal('something')
done()
}, 0)