search.spec.js 3.20 KiB
import Search from "@/api/search.js";
describe("search api", () => {
afterEach(() => {
jest.restoreAllMocks();
});
it("should pass search query to lunrjs index", () => {
const api = new Search();
api.index = {
search: jest.fn(),
};
const mockQuery = "mock query";
api.search(mockQuery);
expect(api.index.search).toBeCalledTimes(1);
expect(api.index.search).toHaveBeenCalledWith(mockQuery);
});
describe("context", () => {
describe("highlight", () => {
it("should use <em> tags to wrap in context highlight", () => {
const api = new Search();
const highlight = api.highlight([{ match: "test" }], "this is a test");
expect(highlight).toEqual("this is a <em>test</em>");
});
it("should return empty string if no context matches", () => {
const api = new Search();
const highlight = api.highlight([], "this is a test");
expect(highlight).toEqual("");
});
it("should use first context match text if no context text", () => {
const api = new Search();
const highlight = api.highlight([
{ match: "test", context: "this is a test" },
]);
expect(highlight).toEqual("this is a <em>test</em>");
});
});
describe("getBestContentContext", () => {
it("should compute best content context based on array length", () => {
const api = new Search();
const mockContext = {
token1: { content: [] },
token2: {
content: [
{ context: "token2 test content" },
{ context: "token3 test content - 2" },
],
},
token3: { content: [{ context: "token3 test content" }] },
};
const bestContentContext = api.getBestContentContext(mockContext);
expect(bestContentContext).toEqual(
mockContext.token2.content[0].context
);
});
it("should return null if empty context provided", () => {
const api = new Search();
const mockContext = {};
const bestContentContext = api.getBestContentContext(mockContext);
expect(bestContentContext).toBeNull();
});
});
it("should compute context", () => {
const api = new Search();
api.contextData = {
mock: {
id: "-mock-",
path: "-mock-",
title: "mock title",
description: "description mock",
content: "content mock content",
},
};
const mockSearchResult = {
ref: "mock",
matchData: {
metadata: {
mock: {
title: { position: [[0, 4]] },
description: { position: [[12, 4]] },
content: { position: [[8, 4]] },
path: { position: [[1, 4]] },
},
},
},
};
const context = api.getContext(mockSearchResult);
expect(context).toEqual({
mock: {
content: [{ context: "content mock content", match: "mock" }],
description: [{ context: "description mock", match: "mock" }],
path: [{ context: "-mock-", match: "mock" }],
title: [{ context: "mock title", match: "mock" }],
},
});
});
});
});