如何使用测试框架Sinon的sandbox.stub
来覆盖,例如navigator.language
或navigator.userAgent
进行测试?
当我尝试使用以下内容时:
suite('agent', function () {
var sandbox;
setup(function () {
// create sandbox environment for mocking about
sandbox = sinon.sandbox.create();
});
teardown(function () {
// restore the environment as it was before
sandbox.restore();
});
test('language', function () {
assert.equal(au.env.agent.language, navigator.language);
if (!navigator.language) assert.equal(au.env.agent.language, 'de');
var lang = "test_URK";
sandbox.stub(window.navigator, 'language', lang);
assert.equal(au.env.agent.language, lang);
});
});
然后我会收到以下错误:无法存根不存在的自有属性语言:
这些存根中没有一个按预期工作:
正在嘲笑导航器对象。
任何提示?
答案 0 :(得分:3)
如Mocking a useragent in javascript?所述,您可以:
navigator.__defineGetter__('language', function(){
return 'foo';
});
或更现代:
Object.defineProperty(navigator, 'language', {
get: function() {return 'bar';}
});
答案 1 :(得分:1)
这里不需要Sinon。问题是,至少Chrome + Safari会阻止对navigator.language(和其他人)的更改,因为它们是只读的。 但是你可以重新创建整个导航器对象,就像你嘲笑它一样。
let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]
var firstArray = [String]()
var secondArray = [String]()
var thirdArray = [String]()
for element in arrayToSplit {
// new array with substrings divided by "|#|" e.g. ["Europe", "Europe", "America", "America"]
let newArray = element.componentsSeparatedByString("|#|")
firstArray.append(newArray[0])
secondArray.append(newArray[1])
thirdArray.append(newArray[2])
}
print("first array: \(firstArray)") // first array: ["Europe", "Europe", "America", "America"]
print("second array: \(secondArray)") // second array: ["France", "Italy", "USA", "Canada"]
print("third array: \(thirdArray)") // third array: ["Paris", "Rome", "Washington", "Ottawa"]
在我的测试中,我会在调用函数之前定义所需的语言。
navigator = {
userLanguage: 'de',
language: 'en'
};
答案 2 :(得分:0)
这对我有用:
In [1]: list1 = [b'R103', b'R102', b'R109', b'R103']
In [2]: list2 = [x.decode("UTF-8") for x in list1]
In [3]: list2
Out[3]: ['R103', 'R102', 'R109', 'R103']