Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 22 additions & 23 deletions example/crontab/crontab.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
// ==UserScript==
// @name crontab example
// @namespace https://bbs.tampermonkey.net.cn/
// @version 0.1.0
// @version 0.2.0
// @description 定时脚本示例
// @author You
// @crontab */15 14-16 * * *
// @grant GM_log
// @grant GM_xmlhttpRequest
// @connect dog.ceo
// @connect httpbun.com
// ==/UserScript==

return new Promise((resolve, reject) => {
// Your code here...
GM_log("下午两点至四点每十五分钟运行一次");

GM_log("下午两点至四点每十五分钟运行一次");

GM_xmlhttpRequest({
url: "https://dog.ceo/api/breeds/image/random",
method: "GET",
responseType: "json",
anonymous: true,
GM_xmlhttpRequest({
url: "https://httpbun.com/get",
method: "GET",
responseType: "json",
anonymous: true,

onload(resp) {
if (typeof resp.response.message !== "string") {
reject("服务器回应错误。");
}
else {
GM_log(`你可能会遇到的狗狗是\n${resp.response.message}`);
resolve();
}
},
onerror(){
reject("服务器回应错误。");
}
});
onload(resp) {
const data = resp.response;
if (resp.status !== 200 || data?.url !== "https://httpbun.com/get") {
reject("服务器回应错误。");
return;
}

GM_log(`定时请求成功:\n${data.url}`);
resolve();
},
onerror() {
reject("服务器回应错误。");
},
});
});
36 changes: 36 additions & 0 deletions tests/example/crontab.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { readFileSync } from "fs";
import { resolve } from "path";
import { describe, expect, it, vi } from "vitest";

type RequestDetails = {
url: string;
onload: (response: { status: number; response: unknown }) => void;
};

const source = readFileSync(resolve(process.cwd(), "example/crontab/crontab.js"), "utf8");
const runExample = new Function("GM_log", "GM_xmlhttpRequest", source) as (
log: (message: string) => void,
request: (details: RequestDetails) => void
) => Promise<void>;

describe("定时脚本示例", () => {
it("定时请求 httpbun 并记录响应 URL", async () => {
const log = vi.fn();
let requestDetails: RequestDetails | undefined;
const result = runExample(log, (details) => {
requestDetails = details;
});

expect(requestDetails?.url).toBe("https://httpbun.com/get");

requestDetails?.onload({
status: 200,
response: {
url: "https://httpbun.com/get",
},
});

await expect(result).resolves.toBeUndefined();
expect(log).toHaveBeenCalledWith("定时请求成功:\nhttps://httpbun.com/get");
});
});
Loading