私はuserAgent
値を変更する方法を見つける必要があります。私はspyOn
のwindow.navigator.userAgent
に行きました。しかし、それは助けにはならない。Jasmine.js Testing - spy on window.navigator.userAgent
JS:
@Injectable()
export class DetectBrowserService {
browserIE: boolean;
constructor() {
this.browserIE = this.detectExplorer();
}
public detectExplorer() {
const brows = window.navigator.userAgent;
const msie = brows.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return true;
}
}
}
スペック:
it('should test window.navigator.userAgent',() => {
const wind = jasmine.createSpy('window.navigator.userAgent');
wind.and.returnValue('1111');
detectBrowserService = TestBed.get(DetectBrowserService);
console.log(window.navigator.userAgent);
});
私は1111
を期待したが、私のブラウザについての本当の情報を得ました。
(http://www.adequatelygood.com/Writing-Testable-JavaScript.htmlのような)厳密な関数にネイティブのapi呼び出しをラップすることをお勧めします。厳密な関数に依存することで、コードをより移植性の高いもの(サーバー側のレンダリング、マルチブラウザの問題など)とテスト可能にすることができます。私はいつもジャスミンでネイティブウィンドウAPIをスパイする問題を抱えていました。 – Sergeon