This is the code I have to so far. I need help with my test function using jest. Visual studio points error to function addTask(“task 3) in the test function. The rest of the code executes fine i.e I am able to display a success message after adding task to the array. The test should pass this requirement of displaying success message only after adding the task to the array.
function successMessage(callback){ callback("Task3"); console.log('success') } var tasks=[]; tasks=[{task_content:"Task 1",status:"open"}, {task_content:"Task 2",status:"closed"}]; //Function addTask adds specific task to tasks array function addTask(add_task) { var status="open"; var new_task={task_content:add_task,status:status}; tasks.push(new_task); console.log("After adding on Task 3"); console.log(tasks); } console.log("Initially Tasks array: "); console.log(tasks); successMessage(addTask) test('success msg', done => { function addTask("task3"){ try{ expect("task 3").toEqual({task_content: 'task3', status: 'open'}) done() }catch(error){ done(error) } } successMessage(addTask); })
Advertisement
Answer
I had converted the above problem into using a promise. I was able to produce the test case with simpler understanding upon using and returning the value of promise rather than callbacks. I am still a noob but this is what has been working for me so far.
var tasks=[]; tasks=[{task_content:"Task 1",status:"open"}, {task_content:"Task 2",status:"closed"}]; function addTask(add_task) { var status="open"; var new_task={task_content:add_task,status:status}; tasks.push(new_task); console.log("After adding on Task 3"); console.log(tasks); } function successMessage(){ console.log('success') } function first(){ var promise1 = new Promise(function(resolve,reject){ resolve(addTask('task 3')) }) return promise1; } function second(){ var promise2 = new Promise(function(resolve,reject) { //addTask("task 3") console.log('success') resolve(second) }) return promise2; } first(); second(); test('promise',()=>{ return first().then(()=>{ expect(second()).resolves.toBe('success') }) //expect(first()).then(second()).resolves.toBe('success') })