Wednesday 23 August 2017

Nock: No match for request. How do I set authentication headers in nock so I can test requests that need basic auth?

I am using nock to mock an api call for an action but I get this error :Nock: No match for request { "method": "post", "url": "URL TO API", "headers": { "accept": "application/json, text/plain, */*", "content-type": "application/x-www-form-urlencoded", "access-control-allow-credentials": true, "authorization": "Basic emFja3lAZ21haWwuY29tOmh1bnRlcjEyMw==", "user-agent": "axios/0.16.2" } } This is the test for login user action:let user = {"email": "zac@gmail.com", "password": "hunter123"}; const middlewares = [thunk]; let credentials = window.btoa(user.email + ':' + user.password); let encrypted = credentials.toString('base64'); let BasicAuth = 'Basic ' + encrypted; const mockStore = configureMockStore(middlewares); afterEach(() => { nock.cleanAll(); }); it('creates LOGIN_USER_SUCCESS after user is logged in', () => { nock(/^.*$/, { reqheaders: { 'Access-Control-Allow-Credentials': true, 'authorization': BasicAuth }, }).post('/auth/login',user).reply(200); const expectedActions = [ {type: types.LOGIN_USER_SUCCESS} ]; const store = mockStore(); return store.dispatch(actions.login(user)).then(() => { expect(store.getActions()).toEqual(expectedActions); }); }); I create a user and encrypt it then add Basic to it and use that as the headers in reqheaders. The problem is that nock can't mock the headers or may be I have set headers wrong. I have tried using matchHeaders but nothing changed. Here is the actual call made using axios:import axios from 'axios'; import httpAdapter from 'axios/lib/adapters/http'; class AuthService { constructor() { axios.defaults.adapter = httpAdapter; let service = axios.create(); service.interceptors.response.use(this.handleSuccess, this.handleError); this.service = service; } handleSuccess(response) { return response; } handleError(error) { return Promise.reject(error); } post(path, user, callback) { return this.service.request({ method: 'POST', url: path, responseType: 'json', data: user }).then((response)=>callback(response.status,response.data)) } login(path, user, callback) { let credentials = window.btoa(user.email + ':' + user.password); let BasicAuth = 'Basic ' + credentials; return this.service.request({ headers:{ 'Authorization':BasicAuth, 'content-type':'application/json' }, method: 'POST', url: path, responseType: 'json', }).then((response)=>callback(response.status,response.data )) } } export default new AuthService; It sends data correctly but I can't mock login using nock. How do I mock login?

Submitted August 24, 2017 at 03:42AM by uptnapishtim

No comments:

Post a Comment