角度测试获得实际的HTTP响应

时间:2018-03-29 07:12:20

标签: angular unit-testing angular-http angular-test angular-testing

我是角度单位测试的新手。我想要做的是从我的API获得实际结果。我检查了this文档,但据我了解,我应该创建模拟响应。这是我的代码,

myService.ts:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div id="leftDiv">
        <div id="deviceInfo">
            <ul id="menu">
            <li>Device Name
                <ul id="deviceName">
                    <li>
                      item 1
                    </li>
                </ul>
            </li>
            <li>Interface
                <ul id="interface">
                    <li>
                      item 2
                    </li>
                </ul>
            </li>
        </ul>
        </div>
        <div id="settingsDiv">
            
        </div>
    </div>
    <div id="mainDiv">
      <div id="mainContainer" class="ui-droppable"><table class="screens ui-draggable" dispcoords="0x0" dispresolution="1920x1080" style="position: relative;"><tbody class="ui-draggable-handle"><tr class="screensRow ui-draggable-handle"><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"><table class="channels ui-draggable ui-resizable ui-draggable-handle" style="width: 478px; height: 358px; font-size: 11px; max-width: 1920px; max-height: 1080px; position: relative; margin-top: -179px;" oncontextmenu="return false;">            <tbody class="ui-draggable-handle"><tr class="channelHeader ui-draggable-handle">              <td colspan="5" class="channelName ui-draggable-handle" id="channel1" audiopid="0x33" audiostream1="format:mp2,type:audio,pid:0x33,width:0,height:0,language:geo" interface="192.168.222.38" method="info" multicast="239.10.20.101" port="6000" protocol="udp" resolution="1920x1080" serviceid="1" servicename="Imedi" serviceprovider="Stereo +" videopid="0x31" videostream="format:H264,type:video,pid:0x31,width:1920,height:1080" aspect="16:9" fps="25">Imedi</td><td colspan="2" class="channelNumber ui-draggable-handle">1</td>            </tr>            <tr class="audioVideo ui-draggable-handle">              <td colspan="5" class="vid ui-draggable-handle"><div class="placeHolder ui-draggable-handle" style="height: 236.813px;"></div></td><td colspan="2" class="sound ui-draggable-handle"><div class="audiodb ui-draggable-handle">              <div class="audioNumbers ui-draggable-handle">                <span class="db max level0 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">0</p></span>                <span class="db high level1 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-6</p></span>                <span class="db level2 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-12</p></span>                <span class="db normal level3 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-20</p></span>                <span class="db level4 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-30</p></span>                <span class="db level5 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-40</p></span>                <span class="db level6 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-50</p></span>                <span class="db low level7 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-60</p></span>              </div>              <div class="audioBackground audioLeft ui-draggable-handle">                <div class="audioCover ui-draggable-handle" style="height: 8%;"></div>              </div>              <div class="audioBackground audioRight ui-draggable-handle">                <div class="audioCover ui-draggable-handle" style="height: 8%;"></div>              </div>              <span class="levels level0 ui-draggable-handle"></span>              <span class="levels level1 ui-draggable-handle"></span>              <span class="levels level2 ui-draggable-handle"></span>              <span class="levels level3 ui-draggable-handle"></span>              <span class="levels level4 ui-draggable-handle"></span>              <span class="levels level5 ui-draggable-handle"></span>              <span class="levels level6 ui-draggable-handle"></span>              <span class="levels level7 ui-draggable-handle"></span>            </div></td>            </tr>            <tr class="channelInfo ui-draggable-handle">              <td class="resolution ui-draggable-handle">Resolution</td><td class="aspect ui-draggable-handle">Aspect</td><td class="fps ui-draggable-handle">FPS</td><td class="vformat ui-draggable-handle">V-Format</td><td class="aformat ui-draggable-handle">A-Format</td><td class="ui-draggable-handle">L</td><td class="ui-draggable-handle">R</td>            </tr>            <tr class="channelInfoValues ui-draggable-handle">              <td class="resolValue ui-draggable-handle">1920x1080</td><td class="aspectValue ui-draggable-handle">16:9</td><td class="fpsValue ui-draggable-handle">25</td><td class="vformatValue ui-draggable-handle">H264</td><td class="aformatValue ui-draggable-handle">MP2</td><td class="leftBarValue ui-draggable-handle">---</td><td class="rightBarValue ui-draggable-handle">---</td>            </tr>          </tbody><div class="resize-sensor ui-draggable-handle" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; z-index: -1; visibility: hidden;"><div class="resize-sensor-expand ui-draggable-handle" style="position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;"><div style="position: absolute; left: 0px; top: 0px; transition: 0s; width: 100000px; height: 100000px;" class="ui-draggable-handle"></div></div><div class="resize-sensor-shrink ui-draggable-handle" style="position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;"><div style="position: absolute; left: 0; top: 0; transition: 0s; width: 200%; height: 200%" class="ui-draggable-handle"></div></div></div><div class="ui-resizable-handle ui-resizable-e ui-draggable-handle" style="z-index: 90;"></div><div class="ui-resizable-handle ui-resizable-s ui-draggable-handle" style="z-index: 90;"></div><div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-draggable-handle" style="z-index: 90;"></div></table></td><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"><table class="channels ui-draggable ui-resizable ui-draggable-handle" style="width: 478px; height: 358px; font-size: 11px; max-width: 1920px; max-height: 1080px; position: relative; margin-top: -179px;" oncontextmenu="return false;">            <tbody class="ui-draggable-handle"><tr class="channelHeader ui-draggable-handle">              <td colspan="5" class="channelName ui-draggable-handle" id="channel2" audiopid="0x33" audiostream1="format:mp2,type:audio,pid:0x33,width:0,height:0,language:geo" interface="192.168.222.38" method="info" multicast="239.10.20.103" port="6000" protocol="udp" resolution="720x576" serviceid="3" servicename="RUSTAVI 2" serviceprovider="Stereo +" videopid="0x31" videostream="format:H264,type:video,pid:0x31,width:720,height:576" aspect="15:11" fps="25">RUSTAVI 2</td><td colspan="2" class="channelNumber ui-draggable-handle">2</td>            </tr>            <tr class="audioVideo ui-draggable-handle">              <td colspan="5" class="vid ui-draggable-handle"><div class="placeHolder ui-draggable-handle" style="width: 383.182px;"></div></td><td colspan="2" class="sound ui-draggable-handle"><div class="audiodb ui-draggable-handle">              <div class="audioNumbers ui-draggable-handle">                <span class="db max level0 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">0</p></span>                <span class="db high level1 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-6</p></span>                <span class="db level2 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-12</p></span>                <span class="db normal level3 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-20</p></span>                <span class="db level4 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-30</p></span>                <span class="db level5 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-40</p></span>                <span class="db level6 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-50</p></span>                <span class="db low level7 ui-draggable-handle"><p style="margin-top: -5.5px;" class="ui-draggable-handle">-60</p></span>              </div>              <div class="audioBackground audioLeft ui-draggable-handle">                <div class="audioCover ui-draggable-handle" style="height: 8%;"></div>              </div>              <div class="audioBackground audioRight ui-draggable-handle">                <div class="audioCover ui-draggable-handle" style="height: 8%;"></div>              </div>              <span class="levels level0 ui-draggable-handle"></span>              <span class="levels level1 ui-draggable-handle"></span>              <span class="levels level2 ui-draggable-handle"></span>              <span class="levels level3 ui-draggable-handle"></span>              <span class="levels level4 ui-draggable-handle"></span>              <span class="levels level5 ui-draggable-handle"></span>              <span class="levels level6 ui-draggable-handle"></span>              <span class="levels level7 ui-draggable-handle"></span>            </div></td>            </tr>            <tr class="channelInfo ui-draggable-handle">              <td class="resolution ui-draggable-handle">Resolution</td><td class="aspect ui-draggable-handle">Aspect</td><td class="fps ui-draggable-handle">FPS</td><td class="vformat ui-draggable-handle">V-Format</td><td class="aformat ui-draggable-handle">A-Format</td><td class="ui-draggable-handle">L</td><td class="ui-draggable-handle">R</td>            </tr>            <tr class="channelInfoValues ui-draggable-handle">              <td class="resolValue ui-draggable-handle">720x576</td><td class="aspectValue ui-draggable-handle">15:11</td><td class="fpsValue ui-draggable-handle">25</td><td class="vformatValue ui-draggable-handle">H264</td><td class="aformatValue ui-draggable-handle">MP2</td><td class="leftBarValue ui-draggable-handle">---</td><td class="rightBarValue ui-draggable-handle">---</td>            </tr>          </tbody><div class="resize-sensor ui-draggable-handle" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; z-index: -1; visibility: hidden;"><div class="resize-sensor-expand ui-draggable-handle" style="position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;"><div style="position: absolute; left: 0px; top: 0px; transition: 0s; width: 100000px; height: 100000px;" class="ui-draggable-handle"></div></div><div class="resize-sensor-shrink ui-draggable-handle" style="position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;"><div style="position: absolute; left: 0; top: 0; transition: 0s; width: 200%; height: 200%" class="ui-draggable-handle"></div></div></div><div class="ui-resizable-handle ui-resizable-e ui-draggable-handle" style="z-index: 90;"></div><div class="ui-resizable-handle ui-resizable-s ui-draggable-handle" style="z-index: 90;"></div><div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-draggable-handle" style="z-index: 90;"></div></table></td><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"></td><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"></td></tr><tr class="screensRow ui-draggable-handle"><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"></td><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"></td><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"></td><td class="screenContainer ui-draggable-handle" style="min-width: 478px; height: 358px;"></td></tr></tbody></table></div>   
</div>

myService.spec.ts:

...

public GetAll = (apiname: string): Observable<Object> => {

return this._http.get("foo/" + apiname,{headers:this.options}); //this.options = newHttpHeaders({'ContentType':'application/json','Accept':'application/json'});
}
...

当我在控制台中写入结果时,它会写入'testData'而不是'data'。正如我之前所说,我希望从我的API获得实际结果,而不是模拟结果。对不起,如果这是一个愚蠢的问题,但我该怎么做?谢谢你的建议。

3 个答案:

答案 0 :(得分:1)

这是获取真实数据的可行解决方案

auth.service.te

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}
  getPost(postId: number): Observable<Post> {
    return this.http.get<Post>(
      `https://jsonplaceholder.typicode.com/posts/${postId}`
    );
  }
}

auth.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClientModule } from '@angular/common/http';
interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}
describe('AuthService', () => {
  let service: AuthService;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
    });
    service = TestBed.inject(AuthService);
  });
  it('should get the data successfully', (done: DoneFn) => {
    service.getPost(1).subscribe((post: Post) => {
      console.log('data is ', post);
      expect(post.id).toEqual(1);
      done();
    });
  });
});

enter image description here 希望有帮助

答案 1 :(得分:0)

如果您没有嘲笑服务电话,您实际上可以等待响应。由于这是异步调用,因此您必须让测试运行器框架知道您正在等待结果。您可以提供done function

示例代码:

it('GetAll() should work', (done) => {
    service.GetAll("items").subscribe(data => { 
        expect(data).toContain("something");
        //expect ...

        done();             // <= done fn invoked. This marks end of test case.
    });
});

更多信息:https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_jasmines_code_done_code_function

答案 2 :(得分:0)

有关刷新刷新请求的通知,那么您可以使用

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.colors as colors
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from matplotlib.cm import ScalarMappable

result=[['4', '24', '16','22', '13'],
 ['13', '41', '25','31', '30'],
 ['83', '91', '83','98', '60']]

result = np.array(result, dtype=np.int)

fig = plt.figure()
ax = fig.add_subplot(111, projection= Axes3D.name)

def make_bar(ax, x0=0, y0=0, width = 0.5, height=1 , cmap="viridis",  
              norm=matplotlib.colors.Normalize(vmin=0, vmax=1), **kwargs ):
    # Make data
    u = np.linspace(0, 2*np.pi, 4+1)+np.pi/4.
    v_ = np.linspace(np.pi/4., 3./4*np.pi, 100)
    v = np.linspace(0, np.pi, len(v_)+2 )
    v[0] = 0 ;  v[-1] = np.pi; v[1:-1] = v_
    x = np.outer(np.cos(u), np.sin(v))
    y = np.outer(np.sin(u), np.sin(v))
    z = np.outer(np.ones(np.size(u)), np.cos(v))

    xthr = np.sin(np.pi/4.)**2 ;  zthr = np.sin(np.pi/4.)
    x[x > xthr] = xthr; x[x < -xthr] = -xthr
    y[y > xthr] = xthr; y[y < -xthr] = -xthr
    z[z > zthr] = zthr  ; z[z < -zthr] = -zthr

    x *= 1./xthr*width; y *= 1./xthr*width
    z += zthr
    z *= height/(2.*zthr)
    #translate
    x += x0; y += y0
    #plot
    ax.plot_surface(x, y, z, cmap=cmap, norm=norm, **kwargs)

def make_bars(ax, x, y, height, width=1):
    widths = np.array(width)*np.ones_like(x)
    x = np.array(x).flatten()
    y = np.array(y).flatten()

    h = np.array(height).flatten()
    w = np.array(widths).flatten()
    norm = matplotlib.colors.Normalize(vmin=0, vmax=h.max())
    for i in range(len(x.flatten())):
        make_bar(ax, x0=x[i], y0=y[i], width = w[i] , height=h[i], norm=norm)


"""Se define lo que va a ser el dibujo o el plot"""
#fig=plt.figure(figsize=(5, 5), dpi=150)
#First subplot
#ax1=fig.add_subplot(111, projection='3d')

xlabels = np.array(['9','12','16a','16b','16c'])
xpos = np.arange(xlabels.shape[0])
ylabels = np.array(['ACN', 'ETOH', 'C-HEX'])
ypos = np.arange(ylabels.shape[0])

xposM, yposM = np.meshgrid(xpos, ypos, copy=False)

zpos=result
zpos = zpos.ravel()

dx=0.5
dy=0.5
dz=zpos

ax.w_xaxis.set_ticks(xpos + dx/2.)
ax.w_xaxis.set_ticklabels(xlabels)

ax.w_yaxis.set_ticks(ypos + dy/2.)
ax.w_yaxis.set_ticklabels(ylabels)

values = np.linspace(0.1, 1., xposM.ravel().shape[0])

#ax1.bar3d(xposM.ravel(), yposM.ravel(), dz*0, dx, dy, dz, shade=True, color=colors)

make_bars(ax, xposM, yposM, dz, width=0.2, )

plt.show()