L
L
Levingstone2020-03-29 13:22:22
JavaScript
Levingstone, 2020-03-29 13:22:22

How to write an asynchronous jest test for action // mobx?

The action itself

addItem = text => {
           axios.post("/task", {
               headers: { "Content-Type": "application/json" },
               text: text
             })
             .then(res => {
               this.arr.push(res.data.task);
             })
             .catch(e => console.log(e));
         };

I tried something like this, it didn't work, I get an error TypeError: Cannot read property 'then' of undefined
describe("STORE", () => {
  it("create new task", () => {
    const store = new Store();
    const text = "test";
    store.addItem(text).then( () => {
    return expect(store.arr.length).toBe(1);
    })
  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-03-29
@Levingstone

Firstly, addItem does not return anything, naturally, you cannot call the then method on anything (undefined), since undefined, in principle, cannot have methods. You need to add a return:

addItem = text => {
           return axios.post("/task", {
               headers: { "Content-Type": "application/json" },
               text: text
             })
             .then(res => {
               this.arr.push(res.data.task);
             })
             .catch(e => console.log(e));
         };

Secondly, jest has a resolves construct for promises
describe("STORE", () => {
  it("create new task", () => {
    const store = new Store();
    const text = "test";
    expect(store.addItem(text)).resolves.toBe(1);
  });
});

And yes, the test will be completely legally failed, the reason is again in the return, but I already propose to deal with this on your own

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question