首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为特定浏览器运行Jasmine测试?

如何为特定浏览器运行Jasmine测试?
EN

Stack Overflow用户
提问于 2017-08-23 19:52:25
回答 1查看 1.1K关注 0票数 1

在我的项目中,我有一些函数可以检测当前使用的浏览器。我想使用Jasmine测试自动测试它们。

如何在选定的浏览器中运行一个特定的测试?

浏览器检测.ts:

代码语言:javascript
复制
export class BrowserDetection {
    public static isMicrosoftInternetExplorer() {
        return this.isBrowser('MSIE ');
    }

    public static isMicrosoftEdge() {
        return this.isBrowser('Edge/')
    }

    public static isGoogleChrome() {
        return this.isBrowser('chrome');
    }

    /**
     *
     * @param browserString Browserstring as it is found in the useragent string.
     * @returns {boolean} Returns true if there is a match for the browserstring.
     */
    private static isBrowser(browserString): boolean {
        let userAgent = window.navigator.userAgent;
        return userAgent.indexOf(browserString) >= 0;
    }
}

浏览器检测.spec.ts:

代码语言:javascript
复制
import {BrowserDetection} from "app/module/browser-detection/browser-detection";

describe('BrowserDetection', () => {
    it('detects google chrome correctly', () => {
        // Arrange
        // TODO: only run this test on google chrome

        // Act
        let result = BrowserDetection.isGoogleChrome();

        // Assert
        expect(result).toBe(true);
    })
});
EN

回答 1

Stack Overflow用户

发布于 2017-08-23 20:08:19

它可以通过单元测试获得全面的覆盖。

首先,可以对isBrowser进行存根,并且可以测试特定于浏览器的方法:

代码语言:javascript
复制
spyOn(BrowserDetection, 'isBrowser');

BrowserDetection.isBrowser.and.returnValue(true);
expect(BrowserDetection.isGoogleChrome()).toBe(true);

BrowserDetection.isBrowser.and.returnValue(false);
expect(BrowserDetection.isGoogleChrome()).toBe(false);

expect(BrowserDetection.isBrowser).toHaveBeenCalledWith('chrome');

然后,可以针对真正的UA字符串测试isBrowser,因为navigator.userAgent不能被存根。

代码语言:javascript
复制
expect(BrowserDetection.isBrowser(navigator.userAgent)).toBe(true);
expect(BrowserDetection.isBrowser(navigator.userAgent.slice(5, -5))).toBe(true);
expect(BrowserDetection.isBrowser('foo')).toBe(false);
expect(BrowserDetection.isBrowser(navigator.userAgent + 'foo')).toBe(false);

或者,BrowserDetection可以是一个使用另一个服务window的服务(静态类无论如何都是反模式的),这样window和它的属性就可以在测试中被模仿,并提供假的UA字符串。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45838986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档