あなたの関数は、DOMから要素を取得します。したがって、あなたのテストでは、そのような要素をDOMで作成しなければなりません。
describe('get_user_input',() => {
beforeEach(() => {
window.document.cookie = 'test_case=';
$("<div class='selector'>test</div>").appendTo("body");
yourFunction();
});
it('should update the cookie with users input if the input is NOT undefined',() => {
expect(window.document.cookie).toEqual('test_case=test');
});
});
しかし
より好ましいソリューションは、あなたの関数からDOM操作を取り除くためにも、この機能を簡単にテスト可能とあまりカップリングになるだろう。
function yourFunction(user_input) {
window.document.cookie = 'user_input=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT';
if (typeof user_input !== "undefined") {
var date = new Date;
user_input = user_input.replace(/(\r\n|\n|\r)/gm, ' ');
date.setDate(date.getDate() + 1);
window.document.cookie = "user_input=" + user_input + ';path=/;expires=' + date.toGMTString();
}
}
そして、それのためのテスト:
describe('get_user_input',() => {
let user_input;
beforeEach(() => {
window.document.cookie = 'test_case=';
user_input = "test";
yourFunction(user_input);
});
it('should update the cookie with users input if the input is NOT undefined',() => {
expect(window.document.cookie).toEqual(`test_case=${user_input}`);
});
});
またはそれ以上 - の機能のうち、window.document.cookie
を移動し、計算された値を返します。そして、この戻り値をwindow.document.cookie
あなたのアプリの他の場所に設定します。
function yourFunction(cookie, user_input) {
let res = 'user_input=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT';
if (typeof user_input !== "undefined") {
var date = new Date;
user_input = user_input.replace(/(\r\n|\n|\r)/gm, ' ');
date.setDate(date.getDate() + 1);
res = "user_input=" + user_input + ';path=/;expires=' + date.toGMTString();
}
return res;
}
describe('get_user_input',() => {
let cookie;
let user_input;
let output;
beforeEach(() => {
cookie = 'test_case=';
user_input = "test";
output = yourFunction(cookie, user_input);
});
it('should update the cookie with users input if the input is NOT undefined',() => {
expect(output).toEqual(`test_case=${user_input}`);
});
});
できるだけシンプルに機能させる。独力責任は揺るがす!
ありがとう!これは私を助けた! – AKr