0

[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon]

I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from.

I am trying to follow the docs for chai-as-promised.

This is a simplification of the vuex action I'm trying to test:

const actions = {
  login: (context, payload) => {
    context.commit('setFlashMessage', "");
    axios.get("https://first-api-call")
      .then((response) => {
        axios.post("https://second-api-call")
          .then((response) => {
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
        });
    },

Notice that the login action has two promises and doesn't return anything. The login action does two things: it sets some state and it changes the route.

The example that I've seen that using chai-as-promised expects that the promise is returned. That is:

var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);

But in my case, login() doesn't return anything, and I'm not sure what I would return if it did.

This is what I have so far:

import store from '@/src/store/store'
describe('login', () => {
  it('bad input', () => {
    store.login({ username: "abcd", password: ""});
    // What is the test I should use?
  }
}
Paulie
  • 1,940
  • 3
  • 20
  • 34

2 Answers2

0

I would return the login response message and make two tests. One to make sure that invalid credentials return a failure message and one to make sure that valid credentials login successfully

aprouja1
  • 1,800
  • 8
  • 17
0

My co-worker and I came up with the solution:

The vuex action needs to return the promise, and they can be chained together:

login: (context, payload) => {
    context.commit('setFlashMessage', "");
    return axios.get("https://first-api-call")
        .then((response) => {
            return axios.post("https://second-api-call")
        })
        .then((response) => {
            // etc...
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
            return {status: "success"};
        });
},

Then we didn't need chai-as-promised because the test looks like this:

it('bad password', () => {
    const result = store.dispatch("login", { username: userName, password: password + "bad" });
    return result.then((response) => {
        expect(response).to.deep.equal({ status: "failed"});
        store.getters.getFlashMessage.should.equal("Error logging in");
    });
});
Paulie
  • 1,940
  • 3
  • 20
  • 34