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
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^canvas$': '<rootDir>/src/__mocks__/canvas.js',
'^canvas$': '<rootDir>/src/__mocks__/node-canvas.js',
},
testMatch: ['**/__tests__/**/*.test.[jt]s?(x)'],
modulePathIgnorePatterns: [
Expand Down
1 change: 1 addition & 0 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
import '@testing-library/jest-dom'
import './src/__mocks__/readableStream.js'
import 'web-streams-polyfill/dist/polyfill.js'
29 changes: 25 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@
"tailwindcss": "^3.4.14",
"ts-jest": "^29.3.2",
"typescript": "5.0.2",
"wait-on": "^7.2.0"
"wait-on": "^7.2.0",
"web-streams-polyfill": "^4.1.0"
},
"engines": {
"node": "^20.0.0"
Expand Down
2 changes: 1 addition & 1 deletion src/__mocks__/canvas.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = jest.genMockFromModule('canvas')
module.exports = {}

module.exports.createCanvas = jest.fn(() => ({
getContext: jest.fn(() => ({
Expand Down
20 changes: 12 additions & 8 deletions src/__mocks__/canvasMock.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
const Canvas = jest.fn(() => ({
getContext: jest.fn(() => ({
class Canvas {
constructor() {
this.width = 100
this.height = 100
}

getContext = jest.fn(() => ({
measureText: jest.fn(() => ({ width: 0 })),
fillText: jest.fn(),
fillRect: jest.fn(),
Expand All @@ -13,12 +18,11 @@ const Canvas = jest.fn(() => ({
translate: jest.fn(),
rotate: jest.fn(),
scale: jest.fn(),
})),
toBuffer: jest.fn(() => Buffer.from([])),
toDataURL: jest.fn(() => ''),
width: 100,
height: 100,
}))
}))

toBuffer = jest.fn(() => Buffer.from([]))
toDataURL = jest.fn(() => '')
}

const createCanvas = jest.fn((width, height) => {
const canvas = new Canvas()
Expand Down
96 changes: 46 additions & 50 deletions src/__tests__/features/chat/difyChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import settingsStore from '../../../features/stores/settings'
import toastStore from '../../../features/stores/toast'
import i18next from 'i18next'
import { Message } from '../../../features/messages/messages'
import { consumeStream } from '../../testUtils'

jest.mock('../../../features/stores/settings', () => ({
getState: jest.fn(),
Expand All @@ -18,17 +19,38 @@ jest.mock('i18next', () => ({
changeLanguage: jest.fn(),
}))

// --- グローバルオブジェクトのモック管理 ---
let originalFetch: typeof global.fetch
let originalTextDecoder: typeof global.TextDecoder
const mockFetch = jest.fn()
global.fetch = mockFetch

const mockDecode = jest.fn()
global.TextDecoder = jest.fn().mockImplementation(() => ({
decode: mockDecode,
}))

beforeAll(() => {
// 元のオブジェクトを保存
originalFetch = global.fetch
originalTextDecoder = global.TextDecoder

// fetch をモック
global.fetch = mockFetch as any // jest.fn() を fetch の型にキャスト

// TextDecoder をモック(クラスとして new できるように)
global.TextDecoder = class {
decode = mockDecode
} as unknown as typeof TextDecoder
})

afterAll(() => {
// 元のオブジェクトに戻す
global.fetch = originalFetch
global.TextDecoder = originalTextDecoder
})
// --- グローバルオブジェクトのモック管理 終了 ---

describe('difyChat', () => {
beforeEach(() => {
jest.clearAllMocks()
mockFetch.mockClear()
mockDecode.mockClear()

const mockSettings = {
selectLanguage: 'ja',
Expand Down Expand Up @@ -79,23 +101,16 @@ describe('difyChat', () => {
},
})

const mockController = {
enqueue: jest.fn(),
close: jest.fn(),
}

const stream = await getDifyChatResponseStream(
testMessages,
'test-api-key',
'https://test-dify-url',
'old-conversation-id'
)

await (stream as any)._startFn(mockController)
const result = await consumeStream(stream)

expect(mockController.enqueue).toHaveBeenCalledWith('こんにちは')
expect(mockController.close).toHaveBeenCalled()
expect(mockReader.releaseLock).toHaveBeenCalled()
expect(result).toBe('こんにちは')

expect(settingsStore.setState).toHaveBeenCalledWith({
difyConversationId: 'test-conversation-id',
Expand Down Expand Up @@ -144,23 +159,17 @@ describe('difyChat', () => {
},
})

const mockController = {
enqueue: jest.fn(),
close: jest.fn(),
}

const stream = await getDifyChatResponseStream(
testMessages,
'test-api-key',
'https://test-dify-url',
'old-conversation-id'
)

await (stream as any)._startFn(mockController)
const result = await consumeStream(stream)

expect(result).toBe('エージェントからの応答')

expect(mockController.enqueue).toHaveBeenCalledWith(
'エージェントからの応答'
)
expect(settingsStore.setState).toHaveBeenCalledWith({
difyConversationId: 'agent-conversation-id',
})
Expand Down Expand Up @@ -192,11 +201,6 @@ describe('difyChat', () => {
},
})

const mockController = {
enqueue: jest.fn(),
close: jest.fn(),
}

const originalConsoleError = console.error
console.error = jest.fn()

Expand All @@ -207,13 +211,12 @@ describe('difyChat', () => {
'old-conversation-id'
)

await (stream as any)._startFn(mockController)
await consumeStream(stream)

expect(console.error).toHaveBeenCalledWith(
'Error parsing JSON:',
expect.any(Error)
)
expect(mockController.close).toHaveBeenCalled()

console.error = originalConsoleError
})
Expand All @@ -232,11 +235,6 @@ describe('difyChat', () => {
},
})

const mockController = {
enqueue: jest.fn(),
close: jest.fn(),
}

const mockAddToast = jest.fn()
;(toastStore.getState as jest.Mock).mockReturnValue({
addToast: mockAddToast,
Expand All @@ -252,42 +250,36 @@ describe('difyChat', () => {
'old-conversation-id'
)

await (stream as any)._startFn(mockController)
await consumeStream(stream)

expect(i18next.t).toHaveBeenCalledWith('Errors.AIAPIError')
expect(mockAddToast).toHaveBeenCalledWith({
message: 'Errors.AIAPIError',
type: 'error',
tag: 'dify-api-error',
})
expect(mockController.close).toHaveBeenCalled()
expect(mockReader.releaseLock).toHaveBeenCalled()

console.error = originalConsoleError
})

it('レスポンスが空の場合にエラーをスローする', async () => {
mockFetch.mockResolvedValueOnce({
// このテストケース用に fetch をモック
const mockFetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
body: null,
})
global.fetch = mockFetch

const mockController = {
enqueue: jest.fn(),
close: jest.fn(),
}

// getDifyChatResponseStream自体はエラーを投げないが、
// 返されたストリームを consume しようとするとエラーになるはず
const stream = await getDifyChatResponseStream(
testMessages,
'test-api-key',
'https://test-dify-url',
'old-conversation-id'
)

await expect(async () => {
await (stream as any)._startFn(mockController)
}).rejects.toThrow('API response from Dify is empty')
const result = await consumeStream(stream)
expect(result).toBe('')
})

it('APIエラーレスポンスを適切に処理する', async () => {
Expand All @@ -305,6 +297,9 @@ describe('difyChat', () => {
addToast: mockAddToast,
})

global.fetch = mockFetch

// getDifyChatResponseStream の呼び出し自体が reject されることを期待
await expect(
getDifyChatResponseStream(
testMessages,
Expand All @@ -316,11 +311,12 @@ describe('difyChat', () => {
'API request to Dify failed with status 401 and body Unauthorized'
)

// toast のアサーションはそのまま残す
expect(i18next.t).toHaveBeenCalledWith('Errors.InvalidAPIKey')
expect(mockAddToast).toHaveBeenCalledWith({
message: 'Errors.InvalidAPIKey',
type: 'error',
tag: 'dify-api-error',
type: 'error',
})
})
})
Expand Down
Loading