1 | const { Spider, defaultPlan } = require("../build/index");
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | function wait(times) {
|
8 | return new Promise((resolve, reject) => {
|
9 | setTimeout(() => {
|
10 | resolve();
|
11 | }, times);
|
12 | });
|
13 | }
|
14 |
|
15 | describe("check if event emitting is normal", () => {
|
16 | test("event 'queueTask' test", () => {
|
17 | let callback = jest.fn();
|
18 |
|
19 | const s = new Spider();
|
20 | s.plan("plan1", () => null);
|
21 | s.plan("plan2", () => null);
|
22 | s.on("queueTask", callback);
|
23 |
|
24 | s.queue("plan1", "http://exampleUrl1.com");
|
25 | s.queue("plan1", "http://exampleUrl2.com");
|
26 | s.queue("plan2", "http://exampleUrl3.com");
|
27 |
|
28 | expect(callback.mock.calls.length).toBe(3);
|
29 | expect(callback.mock.calls[0][0]).toEqual({
|
30 | info: undefined,
|
31 | planName: "plan1",
|
32 | url: "http://exampleUrl1.com",
|
33 | });
|
34 | expect(callback.mock.calls[1][0]).toEqual({
|
35 | info: undefined,
|
36 | planName: "plan1",
|
37 | url: "http://exampleUrl2.com",
|
38 | });
|
39 | expect(callback.mock.calls[2][0]).toEqual({
|
40 | info: undefined,
|
41 | planName: "plan2",
|
42 | url: "http://exampleUrl3.com",
|
43 | });
|
44 | s.end();
|
45 | });
|
46 |
|
47 | test("event 'empty' test", async () => {
|
48 | expect.assertions(5);
|
49 |
|
50 | const mockCallback = jest.fn();
|
51 | const s = new Spider();
|
52 | s.plan("plan1", () => null);
|
53 | s.on("empty", mockCallback);
|
54 |
|
55 | await wait(1000);
|
56 | expect(mockCallback.mock.calls.length).toBe(0);
|
57 | s.queue("plan1", "http://exampleUrl1.com");
|
58 |
|
59 | await wait(1000);
|
60 | expect(mockCallback.mock.calls.length).not.toBe(0);
|
61 | let callNum = mockCallback.mock.calls.length;
|
62 |
|
63 | s.queue("plan1", "http://exampleUrl2.com");
|
64 | await wait(1000);
|
65 | expect(mockCallback.mock.calls.length).not.toBe(0);
|
66 | expect(mockCallback.mock.calls.length > callNum).toBe(true);
|
67 | callNum = mockCallback.mock.calls.length;
|
68 |
|
69 | s.end();
|
70 | expect(mockCallback.mock.calls.length).not.toBe(0);
|
71 | callNum = mockCallback.mock.calls.length;
|
72 | });
|
73 |
|
74 | test("event 'vacant' test", async () => {
|
75 | expect.assertions(5);
|
76 | const mockCallback = jest.fn();
|
77 | const s = new Spider();
|
78 | s.plan("plan1", () => null);
|
79 | s.on("vacant", mockCallback);
|
80 |
|
81 | await wait(1000);
|
82 | expect(mockCallback.mock.calls.length).toBe(0);
|
83 | s.queue("plan1", "http://exampleUrl1.com");
|
84 |
|
85 | await wait(1000);
|
86 | expect(mockCallback.mock.calls.length).not.toBe(0);
|
87 | let callNum = mockCallback.mock.calls.length;
|
88 | s.queue("plan1", "http://exampleUrl2.com");
|
89 |
|
90 | await wait(2000);
|
91 | expect(mockCallback.mock.calls.length).not.toBe(0);
|
92 | expect(mockCallback.mock.calls.length > callNum).toBe(true);
|
93 |
|
94 | s.end();
|
95 | expect(mockCallback.mock.calls.length).not.toBe(0);
|
96 | });
|
97 | });
|