茉莉花+业力测试运行程序:如何测试window.location.href

时间:2018-09-12 11:21:25

标签: angular typescript jasmine karma-jasmine karma-runner

我有一个封装window对象使用的服务:

@Injectable()
export class WindowService {
    constructor(){};
    get window() : Window {
        return window;
    }
    get href(): string {
        return window.location.href;
    }
    set href(url: string) {
        window.location.href = url;
    }
}

然后我进行了以下茉莉花测试:

describe('WindowService Test Suite', () => {
    let windowService: WindowService;

    beforeEach(() => { 
        windowService = new WindowService();
    });

    it('should set the href', () => {
        windowService.href = "/test";
        expect(windowService.href).toBe("/test");
    });
});

问题是,当我设置href时,业力将重定向到该URL,并导致其他测试无法运行。

有人可以给我一些提示,我可以在不重定向的情况下测试此功能吗?

3 个答案:

答案 0 :(得分:1)

您可以做一些简单的技巧:

self._client.get_input_entity(target)

#test 不会重定向您的页面,但会搜索id = test的DIV滚动到该页面。

答案 1 :(得分:0)

测试此问题的唯一方法是能够通过window或通过WindowServiceconstructor中的setter设置为伪造对象。您无法监视或修改window.location ...

答案 2 :(得分:-1)

Window是一个与其他对象一样的对象。您应该可以在测试中像这样模拟它:

import io

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

import numpy as np
import matplotlib.pyplot as plt


def plot_hist():
    """ Create a sample histogram plot and return a bytesio buffer with plot

    Returns
    -------
    BytesIO : in memory buffer with plot image, can be passed to reportlab or elsewhere
    """    
    # from https://matplotlib.org/gallery/lines_bars_and_markers/scatter_masked.html#sphx-glr-gallery-lines-bars-and-markers-scatter-masked-py
    plt.figure(figsize=(7, 2.25))

    N = 100
    r0 = 0.6
    x = 0.9 * np.random.rand(N)
    y = 0.9 * np.random.rand(N)
    area = (20 * np.random.rand(N))**2  # 0 to 10 point radii
    c = np.sqrt(area)
    r = np.sqrt(x * x + y * y)
    area1 = np.ma.masked_where(r < r0, area)
    area2 = np.ma.masked_where(r >= r0, area)
    plt.scatter(x, y, s=area1, marker='^', c=c)
    plt.scatter(x, y, s=area2, marker='o', c=c)
    # Show the boundary between the regions:
    theta = np.arange(0, np.pi / 2, 0.01)
    plt.plot(r0 * np.cos(theta), r0 * np.sin(theta))

    # create buffer and save image to buffer
    # dpi should match the dpi of your PDF, I think 300 is typical otherwise it won't pretty well
    buf = io.BytesIO()
    plt.savefig(buf, format='png', dpi=300)
    buf.seek(0)
    # you'll want to close the figure once its saved to buffer
    plt.close()

    return buf

def add_text(text, style="Normal", fontsize=12):
    """ Adds text with some spacing around it to  PDF report 

    Parameters
    ----------
    text : str
        The string to print to PDF

    style : str
        The reportlab style

    fontsize : int
        The fontsize for the text
    """
    Story.append(Spacer(1, 12))
    ptext = "<font size={}>{}</font>".format(fontsize, text)
    Story.append(Paragraph(ptext, styles[style]))
    Story.append(Spacer(1, 12))

# Use basic styles and the SimpleDocTemplate to get started with reportlab
styles=getSampleStyleSheet()
doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter,
                        rightMargin=inch/2,leftMargin=inch/2,
                        topMargin=72,bottomMargin=18)

# The "story" just holds "instructions" on how to build the PDF
Story=[]

add_text("My Report", style="Heading1", fontsize=24)

# See plot_hist for information on how to get BytesIO object of matplotlib plot
# This code uses reportlab Image function to add and valid PIL input to the report
image_buffer1 = plot_hist()
im = Image(image_buffer1, 7*inch, 2.25*inch)
Story.append(im)

add_text("This text explains something about the chart.")

image_buffer2 = plot_hist()
im = Image(image_buffer2, 7*inch, 2.25*inch)
Story.append(im)

add_text("This text explains something else about another chart chart.")

# This command will actually build the PDF
doc.build(Story)

# should close open buffers, can use a "with" statement in python to do this for you
# if that works better
image_buffer1.close()
image_buffer2.close()

如果没有,您仍然可以使用

重写它
<mat-grid-list cols="6" gutterSize="32px">
    <mat-grid-tile [colspan]="3">
        left
        <mat-grid-list cols="3" gutterSize="8px">
            <mat-grid-tile>1</mat-grid-tile>

            <mat-grid-tile [colspan]="2">2</mat-grid-tile>

            <mat-grid-tile [colspan]="3">3</mat-grid-tile>
        </mat-grid-list>
    </mat-grid-tile>

    <mat-grid-tile [colspan]="3">
        right
        <mat-grid-list cols="3" gutterSize="8px">
            <mat-grid-tile>4</mat-grid-tile>

            <mat-grid-tile [colspan]="2">5</mat-grid-tile>

            <mat-grid-tile [colspan]="3">6</mat-grid-tile>
        </mat-grid-list>
    </mat-grid-tile>
</mat-grid-list>