vuex#createStore JavaScript Examples

The following examples show how to use vuex#createStore. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestQAProjectEditorRunner.test.js    From restqa with MIT License 6 votes vote down vote up
beforeEach(() => {
  mockPost = undefined;
  mockSelectedEnv = undefined;
  store = createStore({
    modules: {
      restqa: {
        state: {},
        actions: {},
        getters: {
          selectedEnv: () => mockSelectedEnv
        }
      }
    }
  });
});
Example #2
Source File: store.js    From vue.draggable.next with MIT License 5 votes vote down vote up
store = createStore({
  namespaced: true,
  modules: {
    nested
  }
})
Example #3
Source File: index.js    From vue3-element-admin with MIT License 5 votes vote down vote up
store = createStore({
  modules
})
Example #4
Source File: App.test.js    From restqa with MIT License 5 votes vote down vote up
describe("App", () => {
  let store;
  let mockPreferences;

  Store.getters.preferences = () => mockPreferences;
  Store.actions.preferences = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
    store = createStore({
      modules: {
        restqa: Store
      }
    });
  });

  test("Enable the gtm tracking if telemetry is enabled", async () => {
    mockPreferences = {telemetry: true};

    const options = {
      global: {
        stubs: ["router-view"],
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(App, options);
    expect(component.exists()).toBeTruthy();

    expect(Store.actions.preferences).toHaveBeenCalledTimes(1);

    component.vm.$options.watch.telemetry.call(
      component.vm,
      mockPreferences.telemetry
    );

    await component.vm.$nextTick();

    expect(mockIsEnabled.value).toBe(true);
  });

  test("Disabled the gtm tracking if telemetry is enabled", async () => {
    mockPreferences = {telemetry: false};

    const options = {
      global: {
        stubs: ["router-view"],
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(App, options);
    expect(component.exists()).toBeTruthy();

    expect(Store.actions.preferences).toHaveBeenCalledTimes(1);

    component.vm.$options.watch.telemetry.call(
      component.vm,
      mockPreferences.telemetry
    );

    await component.vm.$nextTick();

    expect(mockIsEnabled.value).toBe(false);
  });
});
Example #5
Source File: RestQAProjectTree.test.js    From restqa with MIT License 5 votes vote down vote up
describe("RestQAProjectTree", () => {
  let store;
  let mockFeatures;
  let actions = {
    selectedFile: jest.fn(() => {})
  };

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            features: () => mockFeatures
          }
        }
      }
    });
  });

  test("Should show the feature files", async () => {
    mockFeatures = [
      {
        label: "root",
        children: [
          {
            label: "child",
            filename: "root/child"
          }
        ]
      }
    ];

    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };
    const component = mount(RestQAProjectTree, options);

    expect(component.exists()).toBeTruthy();
    await component.vm.$nextTick();

    const tree = component.findComponent({name: "el-tree"});
    expect(tree.vm.data).toEqual(mockFeatures);
    expect(actions.selectedFile).toHaveBeenCalledTimes(0);

    tree.vm.$emit("node-click", mockFeatures[0].children[0]);

    expect(actions.selectedFile).toHaveBeenCalledTimes(1);
    expect(actions.selectedFile.mock.calls[0][1]).toEqual(
      mockFeatures[0].children[0]
    );
  });
});
Example #6
Source File: RestQASelectConfig.test.js    From restqa with MIT License 5 votes vote down vote up
describe("RestQASelectConfig", () => {
  let store;
  let mockEnvs;
  let mockSelectedEnv;
  let actions = {
    selectedEnv: jest.fn((_, env) => (mockSelectedEnv = env))
  };

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            environments: () => mockEnvs,
            selectedEnv: () => mockSelectedEnv
          }
        }
      }
    });
  });

  test("Should show the config environments", async () => {
    mockEnvs = ["local", "uat"];
    mockSelectedEnv = "local";
    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };
    const component = mount(RestQASelectConfig, options);

    expect(component.exists()).toBeTruthy();
    await component.vm.$nextTick();

    const select = component.findComponent(".select");
    const envs = select.findAllComponents(".option");
    expect(envs.length).toEqual(2);
    expect(envs[0].text()).toEqual("local");
    expect(envs[1].text()).toEqual("uat");

    expect(component.vm.$data.env).toEqual("local");

    await component.vm.$nextTick();

    await envs[1].trigger("click");

    await component.vm.$nextTick();

    expect(actions.selectedEnv).toHaveBeenCalledTimes(1);
    expect(actions.selectedEnv.mock.calls[0][1]).toEqual("uat");
  });
});
Example #7
Source File: RestQATeamBlog.test.js    From restqa with MIT License 5 votes vote down vote up
describe("RestQATeamBlog", () => {
  let store;
  let mockTeam;
  let actions = {};

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            info: () => {
              return {
                team: mockTeam
              };
            }
          }
        }
      }
    });
  });

  afterEach(() => {
    mockTeam = null;
  });

  test("renders a team blog article", async () => {
    mockTeam = {
      blog: {
        url: "https://medium.com/restqa-super",
        last: {
          title: "We are doing TDD!",
          date: "2012-12-12 00:00:00",
          image: "https://example.com/img.png",
          author: {
            username: "@Olivierodo",
            avatar: "https://exampple.com/avatar.png"
          },
          url: "https://medium.com/my-article"
        }
      }
    };

    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQATeamBlog, options);

    expect(component.exists()).toBeTruthy();

    expect(component.find(".team-blog").isVisible()).toBeTruthy();
    expect(component.find(".article .title").text()).toEqual(
      "We are doing TDD!"
    );
    expect(component.find(".article .date").text()).toEqual(
      "December 12, 2012"
    );
    expect(component.find(".article img").attributes("src")).toEqual(
      "https://example.com/img.png"
    );
    expect(component.find(".article a").attributes("href")).toEqual(
      "https://medium.com/my-article"
    );
    expect(component.find(".article a").attributes("target")).toEqual("_blank");
    expect(component.find(".author img").attributes("src")).toEqual(
      "https://exampple.com/avatar.png"
    );
    expect(component.find(".blog a").attributes("href")).toEqual(
      "https://medium.com/restqa-super"
    );
    expect(component.find(".blog a").attributes("target")).toEqual("_blank");
  });
});
Example #8
Source File: RestQATeamNote.test.js    From restqa with MIT License 5 votes vote down vote up
describe("RestQATeamNote", () => {
  let store;
  let mockTeam;
  let actions = {};

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            info: () => {
              return {
                team: mockTeam
              };
            }
          }
        }
      }
    });
  });

  afterEach(() => {
    mockTeam = null;
  });

  test("renders a team notes", async () => {
    mockTeam = {
      note: {
        message: "May the force be with you!",
        from: "Obi-Wan Kenobi",
        avatar: "/starwars/obi.jpg"
      }
    };

    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQATeamNote, options);

    expect(component.exists()).toBeTruthy();

    expect(component.find(".team-note").exists()).toBeTruthy();

    expect(component.find(".team-note").isVisible()).toBeTruthy();
    expect(component.find(".message").text()).toEqual(
      '"May the force be with you!"'
    );
    expect(component.find(".from").text()).toEqual("Obi-Wan Kenobi");
    expect(component.find("img").attributes("src")).toEqual(
      "/starwars/obi.jpg"
    );
  });
});
Example #9
Source File: RestQATeamVideo.test.js    From restqa with MIT License 5 votes vote down vote up
describe("RestQATeamVideo", () => {
  let store;
  let mockTeam;
  let actions = {};

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            info: () => {
              return {
                team: mockTeam
              };
            }
          }
        }
      }
    });
  });

  afterEach(() => {
    mockTeam = null;
  });

  test("renders a team video", async () => {
    mockTeam = {
      video: {
        url: "https://www.youtube.com/channel/restqa",
        last: {
          title: "RestQA Channel",
          date: "2021-02-21 00:00:00",
          image: "https://example.com/tdd.png",
          url: "https://www.youtube.com/watch?v=TDD"
        }
      }
    };

    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQATeamVideo, options);

    expect(component.exists()).toBeTruthy();

    expect(component.find(".team-video").isVisible()).toBeTruthy();

    expect(component.find(".video .title").text()).toEqual("RestQA Channel");
    expect(component.find(".video .date").text()).toEqual("February 21, 2021");
    expect(component.find(".video img").attributes("src")).toEqual(
      "https://example.com/tdd.png"
    );
    expect(component.find(".video a").attributes("href")).toEqual(
      "https://www.youtube.com/watch?v=TDD"
    );
    expect(component.find(".video a").attributes("target")).toEqual("_blank");
    expect(component.find(".channel a").attributes("href")).toEqual(
      "https://www.youtube.com/channel/restqa"
    );
    expect(component.find(".channel a").attributes("target")).toEqual("_blank");
  });
});
Example #10
Source File: import-alias.output.js    From vue-cli-plugin-vue-next with MIT License 5 votes vote down vote up
store = createStore({
  state () {
    return {
      count: 1
    }
  }
})
Example #11
Source File: index.js    From WirtBot with GNU Affero General Public License v3.0 4 votes vote down vote up
store = createStore({
  strict: true,
  modules: { alerts },
  state: initialState,
  mutations: {
    disableFirstUse(state) {
      state.dashboard.firstUse = false;
    },
    resetToFirstUse(state) {
      state.firstUse = true;
    },
    setKeys(state, keys) {
      state.keys = keys;
    },
    updateServer(state, server) {
      state.server = merge({ ...state.server }, server);
    },
    removeDevicesWithoutId(state) {
      state.devices = state.devices.filter((device) => device.id);
    },
    removeDevice(state, id) {
      state.devices = state.devices.filter((device) => device.id !== id);
    },
    addDevice(state, device) {
      state.devices = [...state.devices, device];
    },
    updateServerConfig(state, config) {
      state.server = Object.assign(
        {},
        { ...state.server },
        {
          config: config,
        }
      );
    },
    updateDevices(state, devices) {
      for (let device of devices) {
        const indexOfDeviceInState = state.devices.findIndex(
          (deviceInState) => deviceInState.id === device.id
        );
        state.devices.splice(indexOfDeviceInState, 1, device);
      }
    },
    updateDNS(state, dns) {
      let newState = {}
      newState = merge({ ...state.network.dns }, dns);
      state.network.dns = newState
    },
    updateAPI(state, api) {
      state.network.api = merge({ ...state.network.api }, api);
    },
    updateDNSConfig(state, config) {
      state.network.dns.config = config;
    },
    updateDashboard(state, { messages, widgets }) {
      if (messages) {
        state.dashboard.messages = messages;
      }
      if (widgets) {
        state.dashboard.widgets = widgets;
      }
    },
    resetServer(state) {
      // TODO: create a default state and simply load that in
      state.server = initialState.server;
    },
    resetDevices(state) {
      state.devices = initialState.devices;
    },
    resetDNS(state) {
      state.network.dns = initialState.network.dns;
    },
    setVersion(state, version) {
      state.version = version;
    },
  },
  actions: {
    async setKeys({ commit }, keys) {
      commit("setKeys", keys);
    },
    async generateSigningKeys({ commit }) {
      const keys = await generateSigningKeys();
      commit("setKeys", keys);
    },
    async disableFirstUse({ commit }) {
      commit("disableFirstUse");
    },
    async updateDNSName({ commit, dispatch }, name) {
      commit("updateDNS", { name });
      await dispatch("updateDNS");
    },
    async updateAPIHost({ commit }, host) {
      commit("updateAPI", { host });
    },
    async updateDNSIp({ commit, dispatch }, { v4, v6 }) {
      commit("updateDNS", { ip: { v4, v6 } });
      await dispatch("updateDNS");
    },
    async updateDNSIgnoredZones({ commit, dispatch }, ignoredZones) {
      commit("updateDNS", { ignoredZones });
      await dispatch("updateDNS");
    },
    async updateDNSTls({ commit, dispatch }, { tlsName, tls }) {
      commit("updateDNS", { tlsName, tls });
      if (tls == true && !tlsName) {
        return;
      }
      await dispatch("updateDNS");
    },
    async addDashboardMessage({ state, commit }, message) {
      commit("updateDashboard", {
        messages: [...state.dashboard.messages, message],
      });
    },
    async removeDashboardMessage({ state, commit }, message) {
      const messagesWithoutMessage = state.dashboard.messages.filter((msg) => {
        return msg.title !== message.title;
      });
      commit("updateDashboard", { messages: messagesWithoutMessage });
    },
    async addDashboardWidget({ state, commit }, widget) {
      commit("updateDashboard", {
        widgets: [...state.dashboard.widgets, widget],
      });
    },
    async removeDashboardWidget({ state, commit }, widget) {
      const widgetsWithoutWidget = state.dashboard.widgets.filter((wgt) => {
        return wgt !== widget;
      });
      commit("updateDashboard", { widgets: widgetsWithoutWidget });
    },
    async updateServer({ state, commit, dispatch }, server) {
      let keys = {};
      if (
        (!state.server.keys ||
          !state.server.keys.public ||
          !state.server.keys.private) &&
        (!server.keys || !server.keys.public || !server.keys.private)
      ) {
        keys = await getKeys();
        commit("updateServer", Object.assign({}, server, { keys }));
      } else {
        commit("updateServer", server);
      }
      await dispatch("updateServerConfig");
      await dispatch("updateDeviceConfigs");
    },
    async updateDeviceConfigs({ commit, state }) {
      let devices = await Promise.all(
        state.devices.map(async (device) => {
          try {
            return await addConfigToDevice(device, state.server);
          } catch (error) {
            console.error(error);
            return device;
          }
        })
      );
      commit("updateDevices", devices);
    },
    async updateServerConfig({ commit, state, dispatch }) {
      const config = generateServerConfig(
        state.server,
        state.devices.filter((device) => device.ip && device.keys)
      );
      commit("updateServerConfig", config);
      // Since the server config gets updated with every device change, this is a place to trigger remote updates
      // on the WirtBot
      await dispatch("sendConfigUpdatesToAPI");
      await dispatch("updateDNS");
    },
    async updateDNS({ state, commit, dispatch }) {
      commit(
        "updateDNSConfig",
        generateDNSFile(state.server, state.devices, state.network)
      );
      await dispatch("sendDNSUpdatesToApi");
    },
    async sendDNSUpdatesToApi({ state, dispatch }) {
      if (!state.keys || !state.keys.public || !state.keys.private) {
        await dispatch("generateSigningKeys");
      }
      await updateDNSConfigViaApi(
        state.network.dns.config,
        state.network.api.host
      );
    },
    async sendConfigUpdatesToAPI({ state, dispatch }) {
      if (!state.keys || !state.keys.public || !state.keys.private) {
        await dispatch("generateSigningKeys");
      }
      await updateServerViaApi(state.server.config, state.network.api.host);
    },
    async addDevice(
      { commit, dispatch, state },
      { id, name, ip, type, routed, additionalDNSServers, MTU, keys, port }
    ) {
      try {
        if (!keys) {
          keys = await getKeys();
        }
        const newDevice = await addConfigToDevice(
          { id, keys, name, ip, type, routed, additionalDNSServers, MTU, port },
          state.server
        );
        commit("addDevice", newDevice);
        await dispatch("updateServerConfig");
      } catch (error) {
        if (error.message === "No Server") {
          await dispatch(
            "alerts/addError",
            `${i18n.global.t("errors.deviceAdd")} ${i18n.global.t("errors.noServer")}`
          );
        } else {
          await dispatch(
            "alerts/addError",
            `${i18n.global.t("errors.deviceAdd")} ${i18n.global.t("errors.documentation")}`
          );
          console.error(error);
        }
      }
    },
    async updateDevice({ state, commit, dispatch }, newDevice) {
      const devices = await Promise.all(
        state.devices.map(async (device) => {
          if (device.id === newDevice.id) {
            // This is so heavily guarded as to make sure that
            // the server is already set up
            // and the device form completed.
            // Otherwise this would execute while editing the device form
            if (
              newDevice.type &&
              newDevice.ip &&
              newDevice.keys &&
              state.server.port &&
              state.server.keys
            ) {
              return await addConfigToDevice(newDevice, state.server);
            }
            return newDevice;
          }
          return device;
        })
      );
      commit("updateDevices", devices);
      await dispatch("updateServerConfig", devices);
    },
    async removeDevice({ dispatch, commit }, { id }) {
      try {
        commit("removeDevice", id);
        await dispatch("alerts/addSuccess", i18n.global.t("success.deviceRemoved"));
        await dispatch("updateServerConfig");
      } catch (error) {
        await dispatch(
          "alerts/addError",
          `${i18n.global.t("errors.deviceRemove")} ${i18n.global.t("errors.documentation")}`
        );
        console.error(error);
      }
    },
    async removeDevicesWithoutId({ commit }) {
      commit("removeDevicesWithoutId");
    },
    async replaceState({ dispatch, commit }, newState) {
      // Clean the complete state first
      commit("resetDevices");
      commit("resetDNS");
      commit("setKeys", newState.keys);

      // None of these updates should trigger an update automatically!
      // Otherwise the server config will be overwritten which might lead to the admin PC being locked out of the system
      // That is why the commit functions are called directly

      // set the correct server keys
      commit("updateServer", newState.server);
      newState.devices.forEach(async (device) => {
        commit("addDevice", device);
      });
      commit("updateDNS", {
        tlsName: newState.network.dns.tlsName,
        tls: newState.network.dns.tls,
        name: newState.network.dns.name,
        ip: newState.network.dns.ip,
        ignoredZones: newState.network.dns.ignoredZones,
      });

      // here we use a normal dispatch again to trigger config regeneration and API updates
      await dispatch("updateServer");
      await dispatch("updateDNS");
    },
  },

  plugins: [
    createPersistedState({
      filter(stateChange) {
        if (stateChange.type.includes("alerts/")) {
          return false;
        } else {
          return true;
        }
      },
    }),
    versionFromAppPlugin,
  ],
})
Example #12
Source File: RestQAProjectConfig.test.js    From restqa with MIT License 4 votes vote down vote up
describe("RestQAProjectConfig", () => {
  let store;

  Store.actions.config = ({commit}, val) => {
    commit("config", val);
  };

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: Store
      }
    });
  });

  test("Should show the config information, only one environement", async () => {
    let mockConfig = {
      version: "0.0.1",
      metadata: {
        code: "FEATURE",
        name: "feature",
        description: "fff"
      },
      environments: [
        {
          name: "local",
          default: true,
          plugins: [
            {
              name: "@restqa/restqapi",
              config: {
                url: "https://docs.restqa.io"
              }
            }
          ],
          outputs: [
            {
              type: "html",
              enabled: true
            },
            {
              type: "file",
              enabled: true,
              config: {
                path: "restqa-result.json"
              }
            }
          ]
        }
      ]
    };

    store.dispatch("config", mockConfig);

    const options = {
      global: {
        plugins: [store, ElementPlus]
      },
      shallow: false
    };

    const component = mount(RestQAProjectConfig, options);
    expect(
      component.findComponent({name: "card"}).find(".header").text()
    ).toMatch("Project Configuration (LOCAL)");

    expect(component.exists()).toBeTruthy();

    const descriptions = component.findComponent(".config");

    const fields = ["URL", "CODE", "NAME", "DESCRIPTION", "OUTPUTS"].reduce(
      (obj, key) => {
        descriptions.findAll("tr td").forEach((td, i, arr) => {
          if (td.text() == key) {
            obj[key] = arr[i + 1].text();
          }
        });
        return obj;
      },
      {}
    );

    expect(fields["CODE"]).toEqual(mockConfig.metadata.code);
    expect(fields["NAME"]).toEqual(mockConfig.metadata.name);
    expect(fields["DESCRIPTION"]).toEqual(mockConfig.metadata.description);
    expect(fields["URL"]).toEqual("https://docs.restqa.io");
    expect(fields["OUTPUTS"]).toEqual("htmlfile");
  });

  test("Should show the config information from the selected environment", async () => {
    let mockConfig = {
      version: "0.0.1",
      metadata: {
        code: "FEATURE",
        name: "feature",
        description: "fff"
      },
      environments: [
        {
          name: "local",
          default: true,
          plugins: [
            {
              name: "@restqa/restqapi",
              config: {
                url: "http://localhost:3000"
              }
            }
          ],
          outputs: [
            {
              type: "html",
              enabled: true
            },
            {
              type: "file",
              enabled: true,
              config: {
                path: "restqa-result.json"
              }
            }
          ]
        },
        {
          name: "uat",
          plugins: [
            {
              name: "@restqa/faker-plugin",
              config: {
                url: "https://docs.restqa.io"
              }
            },
            {
              name: "@restqa/restqapi",
              config: {
                url: "https://uat.restqa.io"
              }
            }
          ],
          outputs: [
            {
              type: "html",
              enabled: true
            }
          ]
        }
      ]
    };

    store.dispatch("config", mockConfig);
    store.dispatch("selectedEnv", "uat");

    const options = {
      global: {
        plugins: [store, ElementPlus]
      },
      shallow: false
    };

    const component = mount(RestQAProjectConfig, options);
    expect(
      component.findComponent({name: "card"}).find(".header").text()
    ).toMatch("Project Configuration (UAT)");

    expect(component.exists()).toBeTruthy();

    const descriptions = component.findComponent(".config");

    let fields = ["URL", "CODE", "NAME", "DESCRIPTION", "OUTPUTS"].reduce(
      (obj, key) => {
        descriptions.findAll("tr td").forEach((td, i, arr) => {
          if (td.text() == key) {
            obj[key] = arr[i + 1].text();
          }
        });
        return obj;
      },
      {}
    );

    expect(fields["CODE"]).toEqual(mockConfig.metadata.code);
    expect(fields["NAME"]).toEqual(mockConfig.metadata.name);
    expect(fields["DESCRIPTION"]).toEqual(mockConfig.metadata.description);
    expect(fields["URL"]).toEqual("https://uat.restqa.io");
    expect(fields["OUTPUTS"]).toEqual("html");

    store.dispatch("selectedEnv", "local");

    await component.vm.$nextTick();

    expect(
      component.findComponent({name: "card"}).find(".header").text()
    ).toMatch("Project Configuration (LOCAL)");
    fields = ["URL", "CODE", "NAME", "DESCRIPTION", "OUTPUTS"].reduce(
      (obj, key) => {
        descriptions.findAll("tr td").forEach((td, i, arr) => {
          if (td.text() == key) {
            obj[key] = arr[i + 1].text();
          }
        });
        return obj;
      },
      {}
    );

    expect(fields["CODE"]).toEqual(mockConfig.metadata.code);
    expect(fields["NAME"]).toEqual(mockConfig.metadata.name);
    expect(fields["DESCRIPTION"]).toEqual(mockConfig.metadata.description);
    expect(fields["URL"]).toEqual("http://localhost:3000");
    expect(fields["OUTPUTS"]).toEqual("htmlfile");
  });
});
Example #13
Source File: RestQAProjectEditor.test.js    From restqa with MIT License 4 votes vote down vote up
describe("RestQAProjectEditor", () => {
  let store;
  let mockFeatures = jest.fn();
  let actions = {
    selectedFile: jest.fn(() => {})
  };

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            features: () => mockFeatures
          }
        }
      }
    });
  });

  test("Create a new tab", async () => {
    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQAProjectEditor, options);
    expect(component.exists()).toBeTruthy();

    const card = component.findComponent({name: "card"});
    expect(card.vm.title).toBe(null);
    expect(card.vm.loading).toBe(false);

    const empty = card.findComponent({name: "el-empty"});
    expect(empty.vm.description).toBe("Select a feature file");
    //expect(empty.isVisible()).toBe(true)
    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(0);
    expect(component.vm.currentTab).toBe(null);

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-bar.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(1);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-bar.feature");
    expect(component.findComponent({name: "card"}).vm.title).toBe(
      "integration/foo-bar.feature"
    );
    //expect(empty.vm.isVisible()).toBe(false)

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/bar-foo.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(2);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      },
      {
        title: "bar-foo",
        name: "integration/bar-foo.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/bar-foo.feature");
  });

  test("Create a new tab and update the tab name if the content file is unsaved", async () => {
    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQAProjectEditor, options);
    expect(component.exists()).toBeTruthy();

    const card = component.findComponent({name: "card"});
    expect(card.vm.title).toBe(null);
    expect(card.vm.loading).toBe(false);

    const empty = card.findComponent({name: "el-empty"});
    expect(empty.vm.description).toBe("Select a feature file");
    expect(empty.isVisible()).toBe(true);
    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(0);
    expect(component.vm.currentTab).toBe(null);

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-bar.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(1);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-bar.feature");
    expect(component.findComponent({name: "card"}).vm.title).toBe(
      "integration/foo-bar.feature"
    );

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/bar-foo.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(2);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      },
      {
        title: "bar-foo",
        name: "integration/bar-foo.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/bar-foo.feature");

    component.vm.unsaved("integration/foo-bar.feature", true);

    expect(component.vm.tabs[0].title).toBe("foo-bar •");

    component.vm.unsaved("integration/foo-bar.feature", false);

    expect(component.vm.tabs[0].title).toBe("foo-bar");
  });

  test("Using a tab already open instead of opening a new one if it was already open", async () => {
    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQAProjectEditor, options);
    expect(component.exists()).toBeTruthy();

    const card = component.findComponent({name: "card"});
    expect(card.vm.title).toBe(null);
    expect(card.vm.loading).toBe(false);

    const empty = card.findComponent({name: "el-empty"});
    expect(empty.vm.description).toBe("Select a feature file");
    //expect(empty.vm.isVisible()).toBe(true)
    //
    expect(component.vm.tabs).toHaveLength(0);
    expect(component.vm.currentTab).toBe(null);

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-bar.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(1);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-bar.feature");
    expect(component.findComponent({name: "card"}).vm.title).toBe(
      "integration/foo-bar.feature"
    );

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-bar.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(1);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-bar.feature");
  });

  test("Delete a tab", async () => {
    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQAProjectEditor, options);
    expect(component.exists()).toBeTruthy();

    const card = component.findComponent({name: "card"});
    expect(card.vm.title).toBe(null);
    expect(card.vm.loading).toBe(false);

    const empty = card.findComponent({name: "el-empty"});
    expect(empty.vm.description).toBe("Select a feature file");
    //expect(empty.vm.isVisible()).toBe(true)

    expect(component.vm.tabs).toHaveLength(0);
    expect(component.vm.currentTab).toBe(null);

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-bar.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(1);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-bar.feature");
    expect(component.findComponent({name: "card"}).vm.title).toBe(
      "integration/foo-bar.feature"
    );

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/bar-foo.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(2);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      },
      {
        title: "bar-foo",
        name: "integration/bar-foo.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/bar-foo.feature");

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-foo.feature"
    );

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(3);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      },
      {
        title: "bar-foo",
        name: "integration/bar-foo.feature"
      },
      {
        title: "foo-foo",
        name: "integration/foo-foo.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-foo.feature");
    expect(component.findComponent({name: "card"}).vm.title).toBe(
      "integration/foo-foo.feature"
    );

    component.vm.manageTabs("integration/bar-foo.feature", "remove");

    expect(component.vm.tabs).toHaveLength(2);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      },
      {
        title: "foo-foo",
        name: "integration/foo-foo.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-foo.feature");

    component.vm.manageTabs("integration/foo-foo.feature", "remove");

    await component.vm.$nextTick();

    expect(component.vm.tabs).toHaveLength(1);
    expect(component.vm.tabs).toEqual([
      {
        title: "foo-bar",
        name: "integration/foo-bar.feature"
      }
    ]);
    expect(component.vm.currentTab).toBe("integration/foo-bar.feature");
    expect(component.findComponent({name: "card"}).vm.title).toBe(
      "integration/foo-bar.feature"
    );

    component.vm.manageTabs("integration/foo-bar.feature", "remove");
    expect(component.vm.tabs).toHaveLength(0);
    expect(component.vm.currentTab).toBe(null);
  });

  test('given a readonly dashboard then it should display a "Read only" tag', async () => {
    const storeWithReadOnlyDashboard = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            features: () => mockFeatures,
            readOnly: () => true
          }
        }
      }
    });

    const options = {
      global: {
        plugins: [storeWithReadOnlyDashboard, ElementPlus]
      }
    };

    const component = mount(RestQAProjectEditor, options);
    expect(component.exists()).toBeTruthy();
    expect(component.vm.readOnly).toBe(true);

    component.vm.$options.watch.file.call(
      component.vm,
      "integration/foo-bar.feature"
    );
    await component.vm.$nextTick();

    const card = component.findComponent({name: "card"});
    expect(card.vm.tagLabel).toBe("Read only");
  });
});
Example #14
Source File: RestQAProjectInit.test.js    From restqa with MIT License 4 votes vote down vote up
describe("RestQAProjectInit", () => {
  let store;
  let mockConfigAction = jest.fn();

  Store.actions.config = mockConfigAction;

  Service.initialize = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
    store = createStore({
      modules: {
        restqa: Store
      }
    });
  });

  test("Should show an error if the name is not defined when we try to trigger the initialization", async () => {
    const err = new ValidationError("Please share a project name.");
    Service.initialize.mockRejectedValue(err);

    const options = {
      global: {
        plugins: [store, ElementPlus],
        mocks: {
          $notify: jest.fn()
        }
      },
      shallow: false
    };
    const component = mount(RestQAProjectInit, options);

    expect(component.exists()).toBeTruthy();

    const inputs = {
      name: component.findComponent({ref: "form"}).findAll("input")[0],
      description: component.findComponent({ref: "form"}).findAll("input")[1],
      url: component.findComponent({ref: "form"}).findAll("input")[2],
      env: component.findComponent({ref: "form"}).findAll("input")[3],
      btn: component.findComponent({ref: "form"}).find("button")
    };

    expect(component.findComponent({name: "card"}).vm.loading).toBeFalsy();

    await inputs.btn.trigger("click");

    expect(component.findComponent({name: "card"}).vm.loading).toBeTruthy();

    await component.vm.$nextTick();

    expect(Service.initialize).toHaveBeenCalledTimes(1);
    const expectedData = {};
    expect(Service.initialize.mock.calls[0][0]).toEqual(expectedData);

    await component.vm.$nextTick();

    expect(options.global.mocks.$notify).toHaveBeenCalledTimes(1);
    const expectedNotification = {
      title: "Oups",
      message: "Please share a project name.",
      type: "warning"
    };
    expect(options.global.mocks.$notify.mock.calls[0][0]).toEqual(
      expectedNotification
    );
    expect(mockConfigAction).toHaveBeenCalledTimes(0);
  });

  test("Should show an error if the backend has a server error", async () => {
    const err = new Error("Backend error");
    Service.initialize.mockRejectedValue(err);

    const options = {
      global: {
        plugins: [store, ElementPlus],
        mocks: {
          $notify: jest.fn()
        }
      },
      shallow: false
    };
    const component = mount(RestQAProjectInit, options);

    expect(component.exists()).toBeTruthy();

    const inputs = {
      name: component.findComponent({ref: "form"}).findAll("input")[0],
      description: component.findComponent({ref: "form"}).findAll("input")[1],
      url: component.findComponent({ref: "form"}).findAll("input")[2],
      env: component.findComponent({ref: "form"}).findAll("input")[3],
      btn: component.findComponent({ref: "form"}).find("button")
    };

    expect(component.findComponent({name: "card"}).vm.loading).toBeFalsy();

    await inputs.btn.trigger("click");

    expect(component.findComponent({name: "card"}).vm.loading).toBeTruthy();

    await component.vm.$nextTick();

    expect(Service.initialize).toHaveBeenCalledTimes(1);
    const expectedData = {};
    expect(Service.initialize.mock.calls[0][0]).toEqual(expectedData);

    await component.vm.$nextTick();

    expect(options.global.mocks.$notify).toHaveBeenCalledTimes(1);
    const expectedNotification = {
      title: "Oups",
      message: "Backend error",
      type: "error"
    };
    expect(options.global.mocks.$notify.mock.calls[0][0]).toEqual(
      expectedNotification
    );
    expect(mockConfigAction).toHaveBeenCalledTimes(0);
  });

  test("Should initalize the project", async () => {
    Service.initialize.mockResolvedValue({
      folder: "/tmp/project/",
      configuration: "/tmp/project/.restqa.yml"
    });

    const options = {
      global: {
        plugins: [store, ElementPlus],
        mocks: {
          $notify: jest.fn()
        }
      },
      shallow: false
    };
    const component = mount(RestQAProjectInit, options);

    expect(component.exists()).toBeTruthy();

    const inputs = {
      name: component.findComponent({ref: "form"}).findAll("input")[0],
      description: component.findComponent({ref: "form"}).findAll("input")[1],
      url: component.findComponent({ref: "form"}).findAll("input")[2],
      env: component.findComponent({ref: "form"}).findAll("input")[3],
      btn: component.findComponent({ref: "form"}).find("button")
    };

    const expectedData = {
      name: "backend api",
      description:
        "The backend apis used by all the corporate frontend clients",
      url: "https://api.restqa.io",
      env: "prod"
    };

    inputs.name.setValue(expectedData.name);
    inputs.description.setValue(expectedData.description);
    inputs.url.setValue(expectedData.url);
    inputs.env.setValue(expectedData.env);

    expect(component.findComponent({name: "card"}).vm.loading).toBeFalsy();

    await inputs.btn.trigger("click");

    expect(component.findComponent({name: "card"}).vm.loading).toBeTruthy();

    await component.vm.$nextTick();

    expect(component.findComponent({name: "card"}).vm.loading).toBeFalsy();

    expect(Service.initialize).toHaveBeenCalledTimes(1);
    expect(Service.initialize.mock.calls[0][0]).toEqual(expectedData);

    await component.vm.$nextTick();

    expect(options.global.mocks.$notify).toHaveBeenCalledTimes(1);
    const expectedNotification = {
      title: "Let's go!",
      message: "?? Your project has been created successfully!",
      type: "success"
    };
    expect(options.global.mocks.$notify.mock.calls[0][0]).toEqual(
      expectedNotification
    );
    expect(mockConfigAction).toHaveBeenCalledTimes(1);
  });
});
Example #15
Source File: RestQASponsors.test.js    From restqa with MIT License 4 votes vote down vote up
describe("RestQASponsors", () => {
  let store;
  let mockSponsors;
  let actions = {};

  beforeEach(() => {
    store = createStore({
      modules: {
        restqa: {
          state: {},
          actions,
          getters: {
            info: () => {
              return {
                sponsors: mockSponsors
              };
            }
          }
        }
      }
    });
  });

  afterEach(() => {
    mockSponsors = null;
  });

  test("renders a team sponsors", async () => {
    mockSponsors = [
      {
        url: "https://1atalent-consulting.com",
        name: "1RestQA 1 is here! Do your end-to-end API test integration, the right way!",
        logo: "https://atalent-consulting.com/logo.png"
      },
      {
        url: "https://2atalent-consulting.com",
        name: "RestQA 2 is here! Do your end-to-end API test integration, the right way!",
        logo: "https://2atalent-consulting.com/logo.png"
      }
    ];

    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQASponsors, options);

    expect(component.find(".sponsors").exists()).toBeTruthy();
    expect(component.find(".sponsors").isVisible()).toBeTruthy();

    const wrappers = component.findAll(".sponsor");
    expect(wrappers.length).toBe(2);
    expect(wrappers[0].find("img").attributes("src")).toEqual(
      mockSponsors[0].logo
    );
    expect(wrappers[0].find("img").attributes("alt")).toEqual(
      mockSponsors[0].name
    );
    expect(wrappers[0].attributes("href")).toEqual(
      mockSponsors[0].url +
        "?utm_source=dashboard&utm_medium=referral&utm_campaign=restqa"
    );
    expect(wrappers[0].attributes("title")).toEqual(mockSponsors[0].name);
    expect(wrappers[0].attributes("target")).toEqual("_blank");

    expect(wrappers[1].find("img").attributes("src")).toEqual(
      mockSponsors[1].logo
    );
    expect(wrappers[1].find("img").attributes("alt")).toEqual(
      mockSponsors[1].name
    );
    expect(wrappers[1].attributes("href")).toEqual(
      mockSponsors[1].url +
        "?utm_source=dashboard&utm_medium=referral&utm_campaign=restqa"
    );
    expect(wrappers[1].attributes("title")).toEqual(mockSponsors[1].name);
    expect(wrappers[1].attributes("target")).toEqual("_blank");
  });

  test("render no sponsor if we coudlnt fetch any sponsor", async () => {
    const options = {
      global: {
        plugins: [store, ElementPlus]
      }
    };

    const component = mount(RestQASponsors, options);
    expect(component.find(".sponsors").exists()).toBeFalsy();
    const wrappers = component.findAll(".sponsor");
    expect(wrappers.length).toBe(0);
    expect(component.find(".join a").text()).toBe("Your logo here");
    expect(component.find(".join a").attributes("href")).toBe(
      "https://github.com/sponsors/restqa"
    );
  });
});
Example #16
Source File: Steps.test.js    From restqa with MIT License 4 votes vote down vote up
describe("RestQASteps", () => {
  let store;
  let mockSteps;

  Store.getters.steps = () => mockSteps;
  Store.actions.steps = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
    store = createStore({
      modules: {
        restqa: Store
      }
    });
  });

  test("Renders the components without data if the data are not arrived yet", async () => {
    mockSteps = null;

    const options = {
      global: {
        plugins: [store, ElementPlus]
      },
      shallow: false
    };

    const component = mount(Steps, options);
    expect(component.exists()).toBeTruthy();

    expect(Store.actions.steps).toHaveBeenCalledTimes(1);

    const wrappers = component.findAllComponents(RestQAProjectSteps);
    expect(wrappers.length).toBe(3);

    await component.vm.$nextTick();

    expect(wrappers[0].props("keyword")).toBe("given");
    expect(wrappers[0].props("data")).toEqual(null);

    expect(wrappers[1].props("keyword")).toBe("when");
    expect(wrappers[1].props("data")).toEqual(null);

    expect(wrappers[2].props("keyword")).toBe("then");
    expect(wrappers[2].props("data")).toEqual(null);
  });

  test("Renders the components", async () => {
    mockSteps = [
      {
        plugin: "@restqa/restqapi",
        keyword: "Given",
        step: "I have the api gateway",
        comment: "Initiate the api call"
      },
      {
        plugin: "@restqa/faker-plugin",
        keyword: "Given",
        step: "I have the cookie",
        comment: "Adding the cookie"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "When",
        step: "I call the api",
        comment: "I call the api"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "Then",
        step: "The response status is should be {string}",
        comment: "Check the response status"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "Then",
        step: "The response header contains {string}",
        comment: "Check the response headers"
      }
    ];

    const options = {
      global: {
        plugins: [store, ElementPlus]
      },
      shallow: false
    };

    const component = mount(Steps, options);
    expect(component.exists()).toBeTruthy();

    expect(Store.actions.steps).toHaveBeenCalledTimes(1);

    const wrappers = component.findAllComponents(RestQAProjectSteps);
    expect(wrappers.length).toBe(3);

    await component.vm.$nextTick();

    expect(wrappers[0].props("keyword")).toBe("given");
    const expectedGivenData = mockSteps.filter(
      (step) => step.keyword === "Given"
    );
    expect(wrappers[0].props("data")).toEqual(expectedGivenData);

    expect(wrappers[1].props("keyword")).toBe("when");
    const expectedWhenData = mockSteps.filter(
      (step) => step.keyword === "When"
    );
    expect(wrappers[1].props("data")).toEqual(expectedWhenData);

    expect(wrappers[2].props("keyword")).toBe("then");
    const expectedThenData = mockSteps.filter(
      (step) => step.keyword === "Then"
    );
    expect(wrappers[2].props("data")).toEqual(expectedThenData);
  });

  test("filter the list of steps by keyword (steps)", async () => {
    mockSteps = [
      {
        plugin: "@restqa/restqapi",
        keyword: "Given",
        step: "I have the api gateway",
        comment: "Initiate the api instance"
      },
      {
        plugin: "@restqa/faker-plugin",
        keyword: "Given",
        step: "I have the cookie",
        comment: "Adding the cookie"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "When",
        step: "I call the api",
        comment: "I call the api"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "Then",
        step: "The response status is should be {string}",
        comment: "Check the response status"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "Then",
        step: "The response header contains {string}",
        comment: "Check the response headers"
      }
    ];

    const options = {
      global: {
        plugins: [store, ElementPlus]
      },
      shallow: false
    };

    const component = mount(Steps, options);
    expect(component.exists()).toBeTruthy();

    expect(Store.actions.steps).toHaveBeenCalledTimes(1);

    const wrappers = component.findAllComponents(RestQAProjectSteps);
    expect(wrappers.length).toBe(3);

    await component.vm.$nextTick();

    const input = component.findComponent(".search");
    await input.setValue("call");

    expect(wrappers[0].props("keyword")).toBe("given");
    expect(wrappers[0].props("data")).toEqual([]);

    expect(wrappers[1].props("keyword")).toBe("when");
    expect(wrappers[1].props("data")).toEqual([mockSteps[2]]);

    expect(wrappers[2].props("keyword")).toBe("then");
    expect(wrappers[2].props("data")).toEqual([]);
  });

  test("filter the list of steps by keyword (comment)", async () => {
    mockSteps = [
      {
        plugin: "@restqa/restqapi",
        keyword: "Given",
        step: "I have the api gateway",
        comment: "Initiate the api instance"
      },
      {
        plugin: "@restqa/faker-plugin",
        keyword: "Given",
        step: "I have the cookie",
        comment: "Adding the cookie"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "When",
        step: "I call the api",
        comment: "I call the api"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "Then",
        step: "The response status is should be {string}",
        comment: "Check the response status code"
      },
      {
        plugin: "@restqa/restqapi",
        keyword: "Then",
        step: "The response header contains {string}",
        comment: "Check the response headers"
      }
    ];

    const options = {
      global: {
        plugins: [store, ElementPlus]
      },
      shallow: false
    };

    const component = mount(Steps, options);
    expect(component.exists()).toBeTruthy();

    expect(Store.actions.steps).toHaveBeenCalledTimes(1);

    const wrappers = component.findAllComponents(RestQAProjectSteps);
    expect(wrappers.length).toBe(3);

    await component.vm.$nextTick();

    const input = component.findComponent(".search");
    await input.setValue("status code");

    expect(wrappers[0].props("keyword")).toBe("given");
    expect(wrappers[0].props("data")).toEqual([]);

    expect(wrappers[1].props("keyword")).toBe("when");
    expect(wrappers[1].props("data")).toEqual([]);

    expect(wrappers[2].props("keyword")).toBe("then");
    expect(wrappers[2].props("data")).toEqual([mockSteps[3]]);
  });
});