Testing service with multilevel services dependencies #659
-
Hi, I am writing a test for service with dependency of other service with dependency of some service too. Below are the dependencies @Service()
export class MySQLConnection {
connection!: Connection;
@Initializer()
async init() {
this.connection = await createConnection({
type: 'mysql',
database: mysqlEnv.MYSQL_DB,
host: mysqlEnv.MYSQL_HOST,
port: mysqlEnv.MYSQL_PORT,
username: mysqlEnv.MYSQL_USERNAME,
password: mysqlEnv.MYSQL_PASSWORD,
synchronize: false,
.... @Service()
export class VariableDAO {
@Inject(MySQLConnection)
private mySql!: MySQLConnection;
private repository!: Repository<Variable>;
@Initializer([MySQLConnection])
async init() {
this.repository = this.mySql.connection.getRepository(Variable);
}
async getAll(params?: FindManyOptions<Variable>): Promise<Variable[]> {
return this.repository.find(params);
}
} And below is the service I'd like to write a test @Service()
export class VariableService {
@Inject(VariableDAO)
private variableDAO!: VariableDAO;
async getAll(): Promise<Variable[]> {
return this.variableDAO.getAll();
}
} And here's the test describe('Service: VariableService', () => {
let service: VariableService;
const variableDAO = { getAll: jest.fn() };
beforeEach(async () => {
service = configureServiceTest({
service: VariableService,
mocks: [
{
provide: VariableDAO,
useValue: variableDAO,
},
],
});
});
afterEach(() => jest.restoreAllMocks());
it('should return array of Variable', async () => {
variableDAO.getAll.mockReturnValue([]);
const result = await service.getAll();
expect(result).toHaveLength(0);
});
}); When I ran the test, it seems like the real instance of I already configured Jest as told in documentation. Did I miss something? I know it's unrelated, but here is the error returned by Jest. The point is, it seemed like the real instance dependency of VariableDAO is called. anyway, apologize for my bad english
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Could it be that beforeEach has an async callback, but you are really not await-ing for anything? |
Beta Was this translation helpful? Give feedback.
-
It's seems like you've missed environment configuration, it's caused because See https://dev.to/darkmavis1980/how-to-mock-environmental-variables-with-jest-2j3c for example |
Beta Was this translation helpful? Give feedback.
It's seems like you've missed environment configuration, it's caused because
VariableService
importsVariableDAO
which importsMySQLCommection
service which imports yourcleanEnv
and evenVariableDAO
is mocked and not actually instantiated - imports are still loaded and hence yourcleanEnv
executed which leads to this validation error, nothing wrong with library or mocks, you have to configure your environment variables before tests, e.g. injest.config.js
See https://dev.to/darkmavis1980/how-to-mock-environmental-variables-with-jest-2j3c for example