I'm having trouble creating tests for an API built with Express and TypeScript. I keep encountering strange errors during compilation and mocking configurations. Here are my files:
/test/unit/services/episodeService.spec.ts
/*some imports*/
describe('Episodes Service', () => {
let episodesQueryServiceMock: jest.Mocked<typeof episodesQueryService>
let watchTimeInstance: jest.Mocked<WatchTimeInstance>
beforeEach(() =>{
jest.mock('../../../src/services/queries/episodesQueryService')
jest.mock('../../../src/models/')
jest.mock('../../../src/models/WatchTime')
episodesQueryServiceMock = episodesQueryService as jest.Mocked<typeof episodesQueryService>
})
it('When there is no WatchTime, then create it', async ()=> {
const watchTime: WatchTime = watchTimeFactory.build()
(episodesQueryServiceMock.findByUserIdAndEpisodeId as jest.Mock).mockReturnValue(watchTime)
(watchTimeInstance.save as jest.Mock).mockReturnValue(watchTime)
const actual = await episodesService.setWatchTime(watchTime)
})
})
In the code above, I encountered an error in the first line of my test case.
This expression is not callable. Type 'WatchTime' has no call signatures.ts(2349)
The issue seems to be with using a factory to generate random objects for testing, as shown in my factory file below:
./test/factories/watchTime.ts
/*some imports*/
export const watchTimeFactory = Factory.makeFactory<WatchTime>(() => ({
userId: Number(faker.random.numeric()),
episodeId: Number(faker.random.numeric()),
seconds: Number(faker.random.numeric()),
createdAt: new Date(),
updatedAt: new Date()
}))
I initially thought it was a problem with the factory library, but I encountered the same error with two different factory libraries. However, if I move the factory call outside the test case, the error disappears, but a new error arises when running the test:
TypeError: episodesQueryServiceMock.findByUserIdAndEpisodeId.mockReturnValue is not a function
Here are my Jest configurations:
./jest.config.ts
import type {Config} from '@jest/types';
// Sync object
const config: Config.InitialOptions = {
verbose: true,
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
setupFiles: ['<rootDir>/test/setup.ts'],
testEnvironment: 'node',
maxWorkers: 1,
preset: 'ts-jest'
};
export default config;
./test/setup.ts
import dotenv from 'dotenv'
dotenv.config()
process.env.DATABASE = process.env.DATABASE?.replace(/_development/, '_test')
I believe the errors I am facing are related to the configuration settings. Any help would be greatly appreciated.
Thank you!