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.
JavaScript
x
34
34
1
function successMessage(callback){
2
callback("Task3");
3
console.log('success')
4
}
5
var tasks=[];
6
tasks=[{task_content:"Task 1",status:"open"},
7
{task_content:"Task 2",status:"closed"}];
8
9
//Function addTask adds specific task to tasks array
10
function addTask(add_task) {
11
var status="open";
12
var new_task={task_content:add_task,status:status};
13
tasks.push(new_task);
14
console.log("After adding on Task 3");
15
console.log(tasks);
16
17
}
18
console.log("Initially Tasks array: ");
19
console.log(tasks);
20
21
successMessage(addTask)
22
23
test('success msg', done => {
24
function addTask("task3"){
25
try{
26
expect("task 3").toEqual({task_content: 'task3', status: 'open'})
27
done()
28
}catch(error){
29
done(error)
30
}
31
}
32
successMessage(addTask);
33
})
34
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.
JavaScript
1
42
42
1
var tasks=[];
2
tasks=[{task_content:"Task 1",status:"open"},
3
{task_content:"Task 2",status:"closed"}];
4
5
function addTask(add_task) {
6
7
var status="open";
8
var new_task={task_content:add_task,status:status};
9
tasks.push(new_task);
10
console.log("After adding on Task 3");
11
console.log(tasks);
12
13
}
14
function successMessage(){
15
console.log('success')
16
}
17
function first(){
18
var promise1 = new Promise(function(resolve,reject){
19
resolve(addTask('task 3'))
20
})
21
return promise1;
22
}
23
function second(){
24
var promise2 = new Promise(function(resolve,reject) {
25
//addTask("task 3")
26
console.log('success')
27
resolve(second)
28
29
})
30
return promise2;
31
32
}
33
34
first();
35
second();
36
test('promise',()=>{
37
return first().then(()=>{
38
expect(second()).resolves.toBe('success')
39
})
40
//expect(first()).then(second()).resolves.toBe('success')
41
})
42