在我的项目中,我有一些函数可以检测当前使用的浏览器。我想使用Jasmine测试自动测试它们。
如何在选定的浏览器中运行一个特定的测试?
浏览器检测.ts:
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:
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);
})
});发布于 2017-08-23 20:08:19
它可以通过单元测试获得全面的覆盖。
首先,可以对isBrowser进行存根,并且可以测试特定于浏览器的方法:
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不能被存根。
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字符串。
https://stackoverflow.com/questions/45838986
复制相似问题