我是 Jest 的新手,所以如果我的提问没有正确阅读,我深表歉意,我正在对一个 vanilla JS 类的方法进行单元测试,该类引用了类属性“this.original_params”。通过阅读文档和许多其他 Stackoverflow 帖子,我仍然对我必须模拟哪些部分以及这样做的语法感到困惑。我目前正在尝试测试输入值是否为空以及来自 this.original_params 的目标值。
// autocomplete.js
export default class Autocomplete {
constructor(site_config, page_name) {
this.site_config = site_config;
this.page_name = page_name;
this.lat = null;
this.lng = null;
this.original_params = '';
}
init() {
this.original_params = new URLSearchParams(document.querySelector('meta[name="originalParams"]').content);
}
getDestination(inputSelector) {
if (document.querySelector(inputSelector).getAttribute('value') !== '') {
return document.querySelector(inputSelector).value;
}
console.log(this.original_params.has('destination'));
if (this.original_params.has('destination')) {
return this.original_params.get('destination');
}
}
}
我尝试了多种编写测试的方法,但我不明白从哪里开始。这是测试的当前迭代:
// autocomplete.test.js
it('Sets destination if it exists in Original Params', () => {
document.body.innerHTML = `<meta name="original_params" content="siteid=62309&currency=USD&cid=ROCK&useMiles=&checkin=11/12/21&pageSize=15&mapSize=13&groupid=43285&radius=5&nights=3&latitude=26.10879170000000&map=&longitude=-80.10643370000000&destination=Austin, TX, USA"><input type="search" id="address-input" placeholder="Destination" value="" required="true">`;
const original_params = new URLSearchParams(
'<meta name="original_params" content="siteid=62309&currency=USD&cid=ROCK&useMiles=&checkin=11/12/21&pageSize=15&mapSize=13&groupid=43285&radius=5&nights=3&latitude=26.10879170000000&map=&longitude=-80.10643370000000&destination=Austin, TX, USA"></meta>'
);
expect(autocomplete.getDestination('input#address-input')).toEqual('Austin, TX, USA');
});
我得到的错误:
● getDestination › Sets destination if it exists in Original Params
TypeError: this.original_params.has is not a function
80 | return document.querySelector(inputSelector).value;
81 | }
> 82 | console.log(this.original_params.has('destination'));
| ^
83 | if (this.original_params.has('destination')) {
84 | return this.original_params.get('destination');
85 | }
很感谢任何形式的帮助。