在茉莉花测试中嘲笑DirectLine api调用?

问题描述 投票:0回答:1

我目前正在使用我的angular 7 web应用程序中的WebChat.js javascript库来呈现网络聊天界面。我正在尝试对组件进行一些茉莉花测试,并且在模拟库中的某些功能时遇到了一些问题。

这是我的组件的代码:

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

/**
* Declares the WebChat property on the window object.
*/
declare global {
    interface Window {
        WebChat: any;
    }
}

window.WebChat = window.WebChat || {};

@Component({
    selector: 'app-web-chat',
    templateUrl: './web-chat.component.html',
    styleUrls: ['./web-chat.component.css']
})
export class WebChatComponent implements OnInit {
    @ViewChild("botWindow") botWindowElement: ElementRef;

    constructor() { }

    ngOnInit() {
        const directLine = window.WebChat.createDirectLine({
            secret: "mysecretkey",
            webSocket: false
        });

        window.WebChat.renderWebChat(
            {
                directLine: directLine,
                userID: "Agent"
            },
            this.botWindowElement.nativeElement
        );

        directLine
            .postActivity({
                from: { id: "Agent", name: "Agent" },
                text: "command watch",
                type: "message",
                value: "token"
            })
            .subscribe(
                id => console.log(`Posted activity, assigned ID ${id}`),
                error => console.log(`Error posting activity ${error}`)
            );

    }
}

这是我在spec.ts文件中到目前为止所得到的:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { WebChatComponent } from './web-chat.component';

fdescribe('WebChatComponent', () => {
    let component: WebChatComponent;
    let fixture: ComponentFixture<WebChatComponent>;

    beforeEach(async(() => {
        const spy = jasmine.createSpyObj('window.WebChat', ['renderWebChat', 'createDirectLine']);

        TestBed.configureTestingModule({
            declarations: [WebChatComponent],
            providers: [
                { provide: window.WebChat, useValue: spy }
            ]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(WebChatComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

基本上,我正在逐步完成它,目前我遇到了一个错误,说TypeError: window.WebChat.createDirectLine is not a function,但我认为创建一个间谍并在beforeEach部分提供它将处理它。

我是以正确的方式来做这件事的吗?老实说,我不太确定如何有效地模拟DirectLine API在我的WebChatComponent中进行的调用

angular unit-testing jasmine botframework direct-line-botframework
1个回答
0
投票

问题是Web Chat对全球window写了很多,而且测试没有发生这种情况。您所要做的就是确保Web Chat脚本(在您的index.html文件中)加载测试。

为此,请在karma.conf.js中添加:

files: [
    'https://cdn.botframework.com/botframework-webchat/latest/webchat.js',
],

你可能正在使用不同的webchat.js,比如/master/webchat.js。只需使用index.html中的相同内容。

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.