User:Saul/testing
From Organic Design wiki
jest/vue-test-utils
This setup was done using Vue 3 so if you are still using Vue 2 commands may differ.
First ensure that Vue is at least version 3.0.6 on your project vue@3.0.6;
Then install the dependancies:
# At the time of writing vue-jest@next resolves to alpha.7 which requires typescript so alpha.8 is specified directly.
npm i -D @vue/test-utils@next jest vue-jest@5.0.0-alpha.8 babel-jest babel-core@bridge
Example test: test/unit/ListItem.spec.js
import { mount } from "@vue/test-utils";
import ListItem from "../../src/components/ListItem.vue";
const wrapperSlots = mount(ListItem, {
slots: {
default: "Title",
icon: "Icon"
}
});
const wrapper = mount(ListItem);
it("Matches the snapshot.", () => {
expect(wrapperSlots.html()).toMatchSnapshot();
})
it("Renders the title and icon.", () => {
expect(wrapperSlots.html()).toContain("Title");
expect(wrapperSlots.html()).toContain("Icon");
});
it("Renders the icon only when one is present.", () => {
expect(wrapper.find(".icon").exists()).toBe(false)
expect(wrapperSlots.find(".icon").exists()).toBe(true)
});
And to run it:
jest tests/unit --coverage # Parameter can be omitted to run it quicker.
Nightwatch
Install
vue add e2e-nightwatch
And to run the tests:
vue-cli-service test:e2e --env firefox # Parameter can be omitted to use chrome.
Supertest
Supertest is a testing framework for testing express apps.
Install:
npm i --save-dev supertest
Your express app should export the server.
A simple test will look something like this:
const request = require("supertest");
const app = require("../../server/index.js");
it("should return an error for an invalid session", async done => {
const res = await app.post("/interaction/invalidsession/state")
.set('Accept', 'application/json');
expect(res.statusCode).toEqual(400);
expect(res).toHaveProperty("text");
done();
});
If you have a more complicated setup like needing to setup a database first you need to use hooks to ensure everything gets cleaned up:
express.js
// ...
module.exports = async () => {
// Setup the database first
await database();
// express listen
return app.listen(3000);
}
test.spec.js
const request = require("supertest");
const expressApp = require("../../server/index.js");
const sequelize = require("../../server/sequelize.js");
let app = null;
let server = null;
beforeAll(async done => {
server = await expressApp();
app = await request(server);
done();
});
it("should return an error for an invalid session", async done => {
const res = await app.post("/interaction/invalidsession/state")
.set('Accept', 'application/json');
expect(res.statusCode).toEqual(400);
expect(res).toHaveProperty("text");
done();
});
afterAll(async done => {
// Closing the DB connection allows Jest to exit successfully.
await server.close();
await sequelize.close();
done();
});