@hankei6km/jest-mock-nuxt-content
Version:
nuxt-content mock for jest
123 lines (122 loc) • 3.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const MockNamesValues = [
'only',
'without',
'where',
'sortBy',
'limit',
'skip',
'search',
'surround'
];
function setupChainList(chain) {
return {
count() {
return chain.length;
},
at(idx) {
return chain[idx];
},
find(name) {
const idx = chain.findIndex((c) => c.getMockName() === name);
if (idx < 0) {
throw new Error(`${name} mock is not exist in chain`);
}
return chain[idx];
},
findAll(name) {
return setupChainList(chain.filter((c) => c.getMockName() === name));
}
};
}
function setupFetchQue() {
const que = [];
return {
// reset() {
// que.splice(0);
// },
push(f) {
que.push(f);
},
shift() {
const item = que.shift();
if (item) {
return item;
}
return [undefined, undefined, undefined];
}
};
}
function setupMocks(chain, fetch) {
const mocks = {
only: jest.fn(),
without: jest.fn(),
where: jest.fn(),
sortBy: jest.fn(),
limit: jest.fn(),
skip: jest.fn(),
search: jest.fn(),
surround: jest.fn()
};
MockNamesValues.forEach((k) => {
const impl = function () {
mocks[k].mockName(k);
chain.push(mocks[k]);
mocks[k] = jest.fn(impl);
return {
...mocks,
fetch
};
};
mocks[k].mockImplementation(impl);
});
return {
...mocks,
fetch
};
}
// export type ContetMockOptions = {
// keepCalled: boolean;
// };
function mockContent() {
const fetchQue = setupFetchQue();
const mockContent = jest.fn();
const _setup = function () {
mockContent.mockReset().mockImplementation(() => {
const _chain = [];
const mockFetch = jest.fn().mockImplementation(async () => {
return await new Promise((resolve, reject) => {
fetchQue.push([_chain, resolve, reject]);
});
});
return {
...setupMocks(_chain, mockFetch)
};
});
};
_setup();
return {
$content: mockContent,
mockResponse: (res) => {
const [chain, resolve] = fetchQue.shift();
if (chain === undefined || resolve === undefined) {
throw new Error('No request to respond to!');
}
resolve(res);
return new Promise((resolve) =>
// setImmediate is not defined in jsdom env.
// setImmediate(() => resolve(setupChainList(chain)))
setTimeout(() => resolve(setupChainList(chain)), 0));
},
mockError: (reason) => {
const [chain, _resolve, reject] = fetchQue.shift();
if (chain === undefined || reject === undefined) {
throw new Error('No request to respond to!');
}
reject(reason);
return new Promise((resolve) => setTimeout(() => resolve(setupChainList(chain)), 0));
}
};
}
exports.default = mockContent;