forked from extend-chrome/jest-chrome
-
Notifications
You must be signed in to change notification settings - Fork 4
/
demo.test.ts
102 lines (81 loc) · 2.49 KB
/
demo.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { chrome } from '../src'
import { vi, test, expect } from 'vitest'
test('chrome api events', () => {
const listenerSpy = vi.fn()
const sendResponseSpy = vi.fn()
chrome.runtime.onMessage.addListener(listenerSpy)
expect(listenerSpy).not.toBeCalled()
expect(chrome.runtime.onMessage.hasListeners()).toBe(true)
chrome.runtime.onMessage.callListeners(
{ greeting: 'hello' }, // message
{}, // MessageSender object
sendResponseSpy, // SendResponse function
)
expect(listenerSpy).toBeCalledWith(
{ greeting: 'hello' },
{},
sendResponseSpy,
)
expect(sendResponseSpy).not.toBeCalled()
})
test('chrome api functions', () => {
const manifest = {
name: 'my chrome extension',
manifest_version: 2,
version: '1.0.0',
}
chrome.runtime.getManifest.mockImplementation(() => manifest)
expect(chrome.runtime.getManifest()).toEqual(manifest)
expect(chrome.runtime.getManifest).toBeCalled()
})
test('chrome api functions with callback', () => {
const message = { greeting: 'hello?' }
const response = { greeting: 'here I am' }
const callbackSpy = vi.fn()
chrome.runtime.sendMessage.mockImplementation(
(message, callback) => {
callback(response)
},
)
chrome.runtime.sendMessage(message, callbackSpy)
expect(chrome.runtime.sendMessage).toBeCalledWith(
message,
callbackSpy,
)
expect(callbackSpy).toBeCalledWith(response)
})
test('chrome api functions with lastError', () => {
const message = { greeting: 'hello?' }
const response = { greeting: 'here I am' }
// lastError setup
const lastErrorMessage = 'this is an error'
const lastErrorGetter = vi.fn(() => lastErrorMessage)
const lastError = {
get message() {
return lastErrorGetter()
},
}
// mock implementation
chrome.runtime.sendMessage.mockImplementation(
(message, callback) => {
chrome.runtime.lastError = lastError
callback(response)
// lastError is undefined outside of a callback
delete chrome.runtime.lastError
},
)
// callback implementation
const lastErrorSpy = vi.fn()
const callbackSpy = vi.fn(() => {
if (chrome.runtime.lastError) {
lastErrorSpy(chrome.runtime.lastError.message)
}
})
// send a message
chrome.runtime.sendMessage(message, callbackSpy)
expect(callbackSpy).toBeCalledWith(response)
expect(lastErrorGetter).toBeCalled()
expect(lastErrorSpy).toBeCalledWith(lastErrorMessage)
// lastError has been cleared
expect(chrome.runtime.lastError).toBeUndefined()
})