it('returns the data from the response', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      let result;
      service.get('42').subscribe((res) => { result = res; });
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: {
          _id: '42',
          endDate: '2016-11-30',
          userRid: 'me'
        }
      })));
      expect(result).toEqual(new Timesheet({
        _id: '42',
        endDate: '2016-11-30',
        userRid: 'me'
      }));
    });
    it('add a client release date', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      let result: Version;
      service.get().subscribe((res) => { result = res; });
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: [{ id: '2.0.4', name: 'Misty (2.0.4)', releaseDate: '2016-07-15' }]
      })));
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: {
          id: '1.2.0',
          name: 'rusty nail',
          date: '2017-05-10'
        }
      })));
      expect(result.releaseDate).toEqual(moment('2017-05-10'));
    });
        mockBackend.connections.subscribe((mockConnection:MockConnection)=>{

            if(mockConnection.request.url == '/token'){
                expect(mockConnection.request.method).toBe(RequestMethod.Post);
            console.info(mockConnection.request.getBody());
            expect(mockConnection.request.headers.get('Content-Type')).toEqual('x-www-form-urlencoded');
            mockConnection.mockRespond( new Response(new ResponseOptions({body: login_response})));
            }

            
        });
    it('gets the specified project', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      let result;
      service.get('42731138').subscribe((res) => { result = res; });
      expect(connection.request.url).toEqual(`${environment.dataService}/projects/42731138`);
      expect(connection.request.method).toEqual(RequestMethod.Get);
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: {
          _id: '42731138',
          name: 'Deep Geeky Thoughts About Total Control'
        }
      })));
      expect(result).toEqual(new Project({
        _id: '42731138',
        name: 'Deep Geeky Thoughts About Total Control'
      }));
    });
 (connection: MockConnection) => {
   connection.mockRespond(new Response(
     new ResponseOptions({
         body: [
           {
             id: 2,
             username: "username"
           }]
       }
     )));
 });
 it('saves the token if the login is successful', () => {
   let connection: MockConnection;
   mockBackend.connections.subscribe(c => connection = c);
   spyOn(authenticationTokenService, 'set');
   service.login('user', 'password').subscribe((res) => {
     expect(authenticationTokenService.set).toHaveBeenCalledTimes(1);
     expect(authenticationTokenService.set).toHaveBeenCalledWith('IAmToken');
   });
   connection.mockRespond(new Response(new ResponseOptions({
     status: 200,
     body: {
       success: true,
       user: {
         firstName: 'James',
         lastName: 'Jones'
       },
       token: 'IAmToken'
     }
   })));
 });
Example #7
0
                backend.connections.subscribe((connection:MockConnection) => {
                    let mockResponseBody, response;
                    if (connection.request.url === `/${PATHS.authenticate}`) {
                        mockResponseBody = {
                            status: "success",
                            username: username,
                            sessionId: sessionId
                        };
                        response = new Response(new ResponseOptions({body: JSON.stringify(mockResponseBody)}));

                        connection.mockRespond(response);
                    } else {
                        mockResponseBody = {
                            status: "success"
                        };
                        response = new Response(new ResponseOptions({body: JSON.stringify(mockResponseBody)}));

                        connection.mockRespond(response);
                    }
                });
Example #8
0
    public getPointLog(connection: MockConnection) {

        const id = parseInt(connection.request.url.match(/\/api\/player\/([0-9]+)\/pointlog/i)[1], 10);

        let response = new Response(new ResponseOptions({
            body: JSON.stringify(this.pointLogDb.get(id))
        }));

        connection.mockRespond(response);

    }
    backend.connections.subscribe((connection: MockConnection) => {
      const options = new ResponseOptions({
        body: JSON.stringify(MockKnowledgeApi)
      });

      connection.mockRespond(new Response(options));
      expect(connection.request.method).toEqual(RequestMethod.Get);
      expect(connection.request.url).toBe(
        `http://lookup.dbpedia.org/api/search/KeywordSearch` +
                    `?&QueryString=${searchquery}`
      );
    });
Example #10
0
    public get(connection: MockConnection) {

        const id = parseInt(connection.request.url.match(/\/([0-9]+)/i)[1], 10);
        const foundTournament = this.tournamentDb.get(id);

        if (foundTournament) {

            connection.mockRespond(new Response(new ResponseOptions({
                body: JSON.stringify(foundTournament)
            })));

        } else {

            connection.mockError(new ErrorResponse(new ResponseOptions({
                body: 'Tournament not found',
                status: 404
            })));

        }

    }
    mockBackend.connections.subscribe((connection: MockConnection) => {
      expect(connection.request.method).toBe(RequestMethod.Get);
      expect(connection.request.url).toBe(apiUrl);

      connection.mockRespond(
        new Response(
          new ResponseOptions({
            body: testProducts
          })
        )
      );
    });
 mockBackend.connections.subscribe((connection: MockConnection) => {
   if (connection.request.url === 'http://www.test.com/recovery/id/fromerror') {
     expect(connection.request.headers.get('recovered')).toBe('yes', 'did not execute onRequestError when failed');
   } else {
     expect(connection.request.headers.get('recovered'))
     .toBeNull('did execute onRequestError when failed when it shouldnt');
   }
   connection.mockRespond(new Response(new ResponseOptions({
       status: 200,
       body: JSON.stringify('success')},
   )));
 });
Example #13
0
    it(`Logs error on failed ${method}`, async(inject([TestHttpStore, MockBackend], (s: TestHttpStore, b: MockBackend) => {

      const modelData = {id: 123, name: 'foo'};

      const mock = new TestModel(modelData);

      let logSpy = spyOn((s as any).logger, 'error');

      let connection: MockConnection;
      b.connections.subscribe((c: MockConnection) => connection = c);

      const testPromise = s[method](mock)
        .catch(() => {
          expect(logSpy)
            .toHaveBeenCalledWith('Internal Error');
        });
      connection.mockError(new Error('Internal Error'));

      return testPromise;

    })));
 (connection: MockConnection) => {
   connection.mockRespond(new Response(
     new ResponseOptions({
         body: [
           {
             id: 26,
             contentRendered: '<p><b>Hi there</b></p>',
             contentMarkdown: '*Hi there*'
           }]
       }
     )));
 });
    it('sends a request to start the given timer', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      service.getAll({ timesheetId: '1138' }).subscribe();
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: [{
          _id: '42',
          timesheetRid: '1138',
          workDate: '2016-11-30'
        }]
      })));

      service.start({
        _id: '42',
        timesheetRid: '1138'
      }).subscribe();
      expect(connection.request.url).toEqual(`${environment.dataService}/timesheets/1138/taskTimers/42/start`);
      expect(connection.request.method).toEqual(RequestMethod.Post);
    });
Example #16
0
    public get(connection: MockConnection) {

        const id = parseInt(connection.request.url.match(/\/api\/player\/([0-9]+)/i)[1], 10);
        const foundPlayer = this.playerDb.getPlayer(id);

        if (foundPlayer) {

            connection.mockRespond(new Response(new ResponseOptions({
                body: JSON.stringify(foundPlayer)
            })));

        } else {

            connection.mockError(new ErrorResponse(new ResponseOptions({
                body: 'Player not found',
                status: 404
            })));

        }

    }
    it('rethrows non 401 errors', () => {
      let connection: MockConnection;
      token = null;

      spyOn(mockRouter, 'navigate');
      mockBackend.connections.subscribe(c => connection = c);
      let err;
      service.get('http://test.dr.who/companions')
        .subscribe(() => { }, (e) => { err = e; });

      const response = new Response(new ResponseOptions({
        status: 400,
        body: {
          reason: 'I do not like to do things for you'
        }
      }));
      connection.mockError(response as any as Error);
      expect(mockRouter.navigate).not.toHaveBeenCalled();
      expect(err.status).toEqual(400);
      expect(err._body.reason).toEqual('I do not like to do things for you');
    });
Example #18
0
                backend.connections.subscribe((connection:MockConnection) => {
                    // Watch bug: https://github.com/angular/angular/issues/9824
                    let response = new Response(new ResponseOptions({
                        status: 400,
                        type: ResponseType.Error,
                        body: JSON.stringify({
                            "status": "error",
                            "error": "Username or password is missing."
                        })
                    }));

                    connection.mockRespond(response);
                });
	mockBackend.connections.subscribe((connection: MockConnection) => {
		const urlToMatch = `${config.getBaseUri()}/${config.getEndpointHeroes()}`;
		if (connection.request.url !== urlToMatch) {
			return;
		}

		connection.mockRespond(new Response(
			new ResponseOptions({
				body: JSON.stringify(heroes),
				status: 200
			})
		));
	});
        backend.connections.subscribe((c: MockConnection) => { 

            console.debug('Mocking response for ' + c.request.url);

            if (c.request.url == "http://www.angular.at/api/flug?abflugort=Graz&zielort=Hamburg") {

                c.mockRespond(
                    new Response(
                        new ResponseOptions(
                            { body: '[{"id": 1, "abflugort": "Graz", "zielort": "Hamburg", "datum": "2017-01-01"}]' })));

            }
        });
 mockBackend.connections.subscribe((conn: MockConnection) => {
   expect(conn.request.url).toBe(expectedUrl);
   let headers = new Headers({'Content-Type': 'application/json'});
   let mockResponse = new ResponseOptions({
     body: JSON.stringify([{
       "id": 1,
       "name": "Kitchen Sink",
       "type": {"id": 1, "name": "Demonstration"}
     }])
     , status: 200, statusText: "OK", headers: headers
   });
   conn.mockRespond(new Response(mockResponse));
 });
    it('gets all of the stages', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      let result;
      service.getAll().subscribe(res => result = res);
      expect(connection.request.url).toEqual(`${environment.dataService}/stages`);
      expect(connection.request.method).toEqual(RequestMethod.Get);
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: [{
          _id: '42',
          stageNumber: 1,
          name: 'Deep Thought'
        }, {
          _id: '1138',
          stageNumber: 2,
          name: 'Drackonian Crackdown'
        }, {
          _id: '314159',
          stageNumber: 3,
          name: 'Eat Pie'
        }]
      })));
      expect(result).toEqual([new Stage({
        _id: '42',
        stageNumber: 1,
        name: 'Deep Thought'
      }), new Stage({
        _id: '1138',
        stageNumber: 2,
        name: 'Drackonian Crackdown'
      }), new Stage({
        _id: '314159',
        stageNumber: 3,
        name: 'Eat Pie'
      })]);
    });
    it('posts a new user properly', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      let result;
      service.save(new User({
        firstName: 'Baron',
        lastName: 'von Stinky-Head',
        username: 'bvonsh@aol.com',
        password: 'MyHeadSmellsBad'
      })).subscribe(res => result = res);

      expect(connection.request.url).toEqual(`${environment.dataService}/users`);
      expect(connection.request.method).toEqual(RequestMethod.Post);
      expect(JSON.parse(connection.request.getBody())).toEqual({
        firstName: 'Baron',
        lastName: 'von Stinky-Head',
        username: 'bvonsh@aol.com',
        password: 'MyHeadSmellsBad'
      });

      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: {
          _id: '11387651',
          firstName: 'Baron',
          lastName: 'von Stinky-Head',
          username: 'bvonsh@aol.com'
        }
      })));

      expect(result).toEqual(new User({
        _id: '11387651',
        firstName: 'Baron',
        lastName: 'von Stinky-Head',
        username: 'bvonsh@aol.com'
      }));
    });
    it('returns the result of the post', () => {
      let connection: MockConnection;
      mockBackend.connections.subscribe(c => connection = c);

      let result;
      service.save({
        endDate: '2016-12-24',
        userRid: 'me'
      }).subscribe(res => result = res);
      connection.mockRespond(new Response(new ResponseOptions({
        status: 200,
        body: {
          _id: '73',
          endDate: '2016-12-24',
          userRid: 'me'
        }
      })));
      expect(result).toEqual(new Timesheet({
        _id: '73',
        endDate: '2016-12-24',
        userRid: 'me'
      }));
    });
 (connection: MockConnection) => {
   connection.mockRespond(new Response(
     new ResponseOptions({
         body: {
           main: {
             temp: 123,
             temp_max: 130,
             temp_min: 110
           }
         },
         status: 200
       }
     )));
 });
            backend.connections.subscribe((connection: MockConnection) => {
                let options: ResponseOptions = null;

                if (/json$/.test(connection.request.url)) {
                    options = new ResponseOptions({
                        body: JSON.stringify(mockContent)
                    });
                } else if (/md$/.test(connection.request.url)) {
                    options = new ResponseOptions({
                        body: 'Mock docs'
                    });
                }
                connection.mockRespond(new Response(options));
            });
 (connection: MockConnection) => {
   connection.mockRespond(new Response(
     new ResponseOptions({
       body: {
         'id': '0',
         'name': 'Advertising',
         'active': false,
         'effective_start_date': '2016-10-01',
         'effective_end_date': '2017-10-01',
         'enforce_dates': true
       }
     }
     )));
 });
 mockBackend.connections.subscribe((c: MockConnection) => {
   expect(c.request.url).toBe('http://localhost:3000/api/auth/local');
   expect(c.request.headers.get('Content-Type')).toBe('application/json')
   expect(c.request.getBody()).toBe(JSON.stringify({ email: 'test@test.com', password: '12345' }));
   let mockResponseBody: IJsendResponse = {
     status: 'fail',
     data: {
       'password': 'This password is not correct.'
     },
     message: ''
   };
   let response = new ResponseOptions({body: JSON.stringify(mockResponseBody), status: 401});
   c.mockRespond(new Response(response));
 });
		backend.connections.subscribe((connection: MockConnection) => {
			const options = new ResponseOptions({
				body: JSON.stringify(result)
			});
			connection.mockRespond(new Response(options));
			expect(connection.request.method).toEqual(RequestMethod.Get);
			expect(connection.request.url).toEqual(
				`https://api.loklak.org/api/suggest.json` +
									`?q=${query}` +
									`&callback=JSONP_CALLBACK` +
									`&minified=true` +
									`&order=desc` +
									`&orderby=query_count`);
		});
Example #30
0
			mockBackend.connections.subscribe((connection: MockConnection) => {
				
				//Check url and request was correct
				expect(connection.request.method).toBe(RequestMethod.Delete);
				expect(connection.request.url).toBe("/api/v1/users?userId=5696d1ab1300d90100721891");
				
				//Send mock response
				connection.mockRespond(new Response(new ResponseOptions({
					headers: new Headers({
						"Content-Type": "application/json"
					}),
					body: {}
				})));
			});