Skip to content

Commit b73d6fb

Browse files
authored
Create aiModel.test.js
1 parent c03968a commit b73d6fb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

tests/aiModel.test.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// tests/aiModel.test.js - Unit tests for AI Model module
2+
3+
import AIModel from '../src/space/aiModel';
4+
import * as tf from '@tensorflow/tfjs'; // Import TensorFlow.js
5+
6+
jest.mock('@tensorflow/tfjs'); // Mock TensorFlow.js for testing
7+
8+
describe('AIModel', () => {
9+
let aiModel;
10+
const modelPath = 'path/to/model.json';
11+
12+
beforeEach(() => {
13+
aiModel = new AIModel(modelPath);
14+
});
15+
16+
test('should initialize the model', async () => {
17+
const mockModel = { predict: jest.fn() };
18+
tf.loadLayersModel.mockResolvedValue(mockModel); // Mock the model loading
19+
20+
await aiModel.initialize();
21+
expect(tf.loadLayersModel).toHaveBeenCalledWith(modelPath);
22+
expect(aiModel.model).toBe(mockModel);
23+
});
24+
25+
test('should throw an error if model initialization fails', async () => {
26+
tf.loadLayersModel.mockRejectedValue(new Error('Failed to load model'));
27+
28+
await expect(aiModel.initialize()).rejects.toThrow('Failed to initialize AI model');
29+
});
30+
31+
test('should preprocess data correctly', () => {
32+
const inputData = [[1, 2, 3], [4, 5, 6]];
33+
const expectedTensor = tf.tensor(inputData);
34+
35+
const tensorData = aiModel.preprocessData(inputData);
36+
expect(tensorData).toEqual(expectedTensor);
37+
});
38+
39+
test('should make predictions', async () => {
40+
const mockModel = { predict: jest.fn().mockReturnValue(tf.tensor([[0.5]])) };
41+
aiModel.model = mockModel; // Set the mocked model
42+
43+
const inputData = [[1, 2, 3]];
44+
const processedData = aiModel.preprocessData(inputData);
45+
await aiModel.analyze(inputData);
46+
47+
expect(mockModel.predict).toHaveBeenCalledWith(processedData);
48+
});
49+
50+
test('should throw an error if model is not initialized before prediction', async () => {
51+
const inputData = [[1, 2, 3]];
52+
53+
await expect(aiModel.analyze(inputData)).rejects.toThrow('AI model is not initialized');
54+
});
55+
56+
test('should throw an error during analysis if prediction fails', async () => {
57+
const mockModel = { predict: jest.fn().mockImplementation(() => { throw new Error('Prediction error'); }) };
58+
aiModel.model = mockModel; // Set the mocked model
59+
60+
const inputData = [[1, 2, 3]];
61+
await expect(aiModel.analyze(inputData)).rejects.toThrow('Failed to analyze data');
62+
});
63+
});

0 commit comments

Comments
 (0)