Lib de testes para Javascript e Typescript
URL: https://jestjs.io
Uso
Exemplo básico
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
Mock de módulos
https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options
jest.mock('./typeOrm.config', () => ({
__esModule: true, // this property makes it work as a module
default: {
// initialize method of an object exported at typeOrm
initialize: jest.fn(),
},
// Retain the actual implementation
postgresSettings: jest.requireActual('./typeOrm.config').postgresSettings,
}));
typeOrm.config.ts
:
import { join } from 'path'
import { DataSource } from 'typeorm'
import { config } from 'dotenv'
config()
export const postgresSettings = {
host: process.env.POSTGRES_HOST,
port: 5432,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
}
export default new DataSource({
type: 'postgres',
host: postgresSettings.host,
port: 5432,
username: postgresSettings.username,
password: postgresSettings.password,
database: postgresSettings.database,
entities: [join(__dirname, '../', '**', '*.entity.{ts,js}')],
migrations: [__dirname + '/migrations/*.ts'],
migrationsRun: true,
})
// DataSource has a method called initialize()
Table tests
const { extractUrls } = require("../src/extractUrls");
describe("extractUrls (Table-driven tests array format)", () => {
it.each([
["Go to https://knowledge.com", ["https://knowledge.com"]],
[
"Go to https://knowledge.com and https://world.org",
["https://knowledge.com", "https://world.org"],
],
["Go to http://knowledge.com", ["http://knowledge.com"]],
["Go to google.com", ["google.com"]],
])("extractUrls(%s)", (message, expectedUrls) => {
const extractedUrls = extractUrls(message);
expect(extractedUrls).toEqual(expectedUrls);
});
});
Rodando testes específicos (padrão)
Use --testPathPattern
para dar match no nome do arquivo (aceita wildcard *
)
Use -t
para dar match no nome do teste
Exemplo:
--testPathPattern=item_processor -t "repository with expected params"