Logo de Writing Tests

Writing Tests

Comunidade
NTCoding
writing-tests

Principles for writing effective, maintainable tests. Covers naming conventions, assertion best practices, and comprehensive edge case checklists. Based on BugMagnet by Gojko Adzic. Triggers on: writing any test, 'add tests', test review, test naming, assertion choices, edge case coverage, 'what should I test', test structure decisions.

Visão geral

Publicado porNTCoding
Repositórioclaude-skillz
Nome da habilidadewriting-tests
Estrelas
356
Forks
47
Arquivos incluídos
Somente instruções
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Completa em si mesma

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por NTCoding no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Writing Tests no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/NTCoding/claude-skillz/tree/main/writing-tests
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/NTCoding/claude-skillz.git /tmp/claude-skillz
mkdir -p .claude/skills
cp -r /tmp/claude-skillz/writing-tests .claude/skills/writing-tests
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Writing Tests em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Writing Tests automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Writing Tests não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Writing Tests

How to write tests that catch bugs, document behavior, and remain maintainable.

Based on BugMagnet by Gojko Adzic. Adapted with attribution.

Critical Rules

🚨 Test names describe outcomes, not actions. "returns empty array when input is null" not "test null input". The name IS the specification.

🚨 Assertions must match test titles. If the test claims to verify "different IDs", assert on the actual ID values—not just count or existence.

🚨 Assert specific values, not types. expect(result).toEqual(['First.', ' Second.']) not expect(result).toBeDefined(). Specific assertions catch specific bugs.

🚨 One concept per test. Each test verifies one behavior. If you need "and" in your test name, split it.

🚨 Bugs cluster together. When you find one bug, test related scenarios. The same misunderstanding often causes multiple failures.

When This Applies

  • Writing new tests
  • Reviewing test quality
  • During TDD RED phase (writing the failing test)
  • Expanding test coverage
  • Investigating discovered bugs

Test Naming

Pattern: [outcome] when [condition]

Good Names (Describe Outcomes)

returns empty array when input is null
throws ValidationError when email format invalid
calculates tax correctly for tax-exempt items
preserves original order when duplicates removed

Bad Names (Describe Actions)

test null input           // What about null input?
should work               // What does "work" mean?
handles edge cases        // Which edge cases?
email validation test     // What's being validated?

The Specification Test

Your test name should read like a specification. If someone reads ONLY the test names, they should understand the complete behavior of the system.

Assertion Best Practices

Assert Specific Values

typescript
// ❌ WEAK - passes even if completely wrong data
expect(result).toBeDefined()
expect(result.items).toHaveLength(2)
expect(user).toBeTruthy()

// ✅ STRONG - catches actual bugs
expect(result).toEqual({ status: 'success', items: ['a', 'b'] })
expect(user.email).toBe('test@example.com')

Match Assertions to Test Title

typescript
// ❌ TEST SAYS "different IDs" BUT ASSERTS COUNT
it('generates different IDs for each call', () => {
  const id1 = generateId()
  const id2 = generateId()
  expect([id1, id2]).toHaveLength(2)  // WRONG: doesn't check they're different!
})

// ✅ ACTUALLY VERIFIES DIFFERENT IDs
it('generates different IDs for each call', () => {
  const id1 = generateId()
  const id2 = generateId()
  expect(id1).not.toBe(id2)  // RIGHT: verifies the claim
})

Avoid Implementation Coupling

typescript
// ❌ BRITTLE - tests implementation details
expect(mockDatabase.query).toHaveBeenCalledWith('SELECT * FROM users WHERE id = 1')

// ✅ FLEXIBLE - tests behavior
expect(result.user.name).toBe('Alice')

Test Structure

Arrange-Act-Assert

typescript
it('calculates total with tax for non-exempt items', () => {
  // Arrange: Set up test data
  const item = { price: 100, taxExempt: false }
  const taxRate = 0.1

  // Act: Execute the behavior
  const total = calculateTotal(item, taxRate)

  // Assert: Verify the outcome
  expect(total).toBe(110)
})

One Concept Per Test

typescript
// ❌ MULTIPLE CONCEPTS - hard to diagnose failures
it('validates and processes order', () => {
  expect(validate(order)).toBe(true)
  expect(process(order).status).toBe('complete')
  expect(sendEmail).toHaveBeenCalled()
})

// ✅ SINGLE CONCEPT - clear failures
it('accepts valid orders', () => {
  expect(validate(validOrder)).toBe(true)
})

it('rejects orders with negative quantities', () => {
  expect(validate(negativeQuantityOrder)).toBe(false)
})

it('sends confirmation email after processing', () => {
  process(order)
  expect(sendEmail).toHaveBeenCalledWith(order.customerEmail)
})

Edge Case Checklists

When testing a function, systematically consider these edge cases based on input types.

Numbers

  • Zero
  • Negative numbers
  • Very large numbers (near MAX_SAFE_INTEGER)
  • Very small numbers (near MIN_SAFE_INTEGER)
  • Decimal precision (0.1 + 0.2)
  • NaN
  • Infinity / -Infinity
  • Boundary values (off-by-one at limits)

Strings

  • Empty string ""
  • Whitespace only " "
  • Very long strings (10K+ characters)
  • Unicode: emojis 👨‍👩‍👧‍👦, RTL text, combining characters
  • Special characters: quotes, backslashes, null bytes
  • SQL/HTML/script injection patterns
  • Leading/trailing whitespace
  • Mixed case sensitivity

Collections (Arrays, Objects, Maps)

  • Empty collection [], {}
  • Single element
  • Duplicates
  • Nested structures
  • Circular references
  • Very large collections (performance)
  • Sparse arrays
  • Mixed types in arrays

Dates and Times

  • Leap years (Feb 29)
  • Daylight saving transitions
  • Timezone boundaries
  • Midnight (00:00:00)
  • End of day (23:59:59)
  • Year boundaries (Dec 31 → Jan 1)
  • Invalid dates (Feb 30, Month 13)
  • Unix epoch edge cases
  • Far future/past dates

Null and Undefined

  • null input
  • undefined input
  • Missing optional properties
  • Explicit undefined vs missing key

Domain-Specific

  • Email: valid formats, edge cases (plus signs, subdomains)
  • URLs: protocols, ports, special characters, relative paths
  • Phone numbers: international formats, extensions
  • Addresses: Unicode, multi-line, missing components
  • Currency: rounding, different currencies, zero amounts
  • Percentages: 0%, 100%, over 100%

Violated Domain Constraints

These test implicit assumptions in your domain:

  • Uniqueness violations (duplicate IDs, emails)
  • Missing required relationships (orphaned records)
  • Ordering violations (events out of sequence)
  • Range breaches (age -1, quantity 1000000)
  • State inconsistencies (shipped but not paid)
  • Format mismatches (expected JSON, got XML)
  • Temporal ordering (end before start)

Typed Property Validation

When testing code that validates properties against type constraints (e.g., validating route: string in an interface):

Wrong-type literals:

  • Numeric literal when string expected (route = 123)
  • Boolean literal when string expected (route = true)
  • String literal when number expected (count = 'five')
  • String literal when boolean expected (enabled = 'yes')

Non-literal expressions:

  • Template literal (route = `/path/${id}`)
  • Variable reference (route = someVariable)
  • Function call (route = getRoute())
  • Computed property (route = config.path)

Correct type:

  • Valid literal of correct type (route = '/orders')
  • Edge values (empty string '', zero 0, false)

Why this matters: A common bug pattern is validating "is this a literal?" without checking "is this the RIGHT TYPE of literal?"

  • hasLiteralValue() returns true for 123, true, and 'string'
  • hasStringLiteralValue() returns true only for 'string'

When an interface specifies property: string, validation must reject numeric and boolean literals, not just non-literal expressions.

Bug Clustering

When you discover a bug, don't stop—explore related scenarios:

  1. Same function, similar inputs - If null fails, test undefined, empty string
  2. Same pattern, different locations - If one endpoint mishandles auth, check others
  3. Same developer assumption - If off-by-one here, check other boundaries
  4. Same data type - If dates fail at DST, check other time edge cases

When Tempted to Cut Corners

  • If your test name says "test" or "should work": STOP. What outcome are you actually verifying? Name it specifically.

  • If you're asserting toBeDefined() or toBeTruthy(): STOP. What value do you actually expect? Assert that instead.

  • If your assertion doesn't match your test title: STOP. Either fix the assertion or rename the test. They must agree.

  • If you're testing multiple concepts in one test: STOP. Split it. Future you debugging a failure will thank you.

  • If you found a bug and wrote one test: STOP. Bugs cluster. What related scenarios might have the same problem?

  • If you're skipping edge cases because "that won't happen": STOP. It will happen. In production. At 3 AM.

Integration with Other Skills

With TDD Process: This skill guides the RED phase—how to write the failing test well.

With Software Design Principles: Testable code follows design principles. Hard-to-test code often has design problems.

Perguntas frequentes

O que a habilidade de IA Writing Tests faz?

Principles for writing effective, maintainable tests. Covers naming conventions, assertion best practices, and comprehensive edge case checklists. Based on BugMagnet by Gojko Adzic. Triggers on: writing any test, 'add tests', test review, test naming, assertion choices, edge case coverage, 'what should I test', test structure decisions.

Por que usar Writing Tests no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Writing Tests é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Writing Tests no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/NTCoding/claude-skillz/tree/main/writing-tests. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Writing Tests?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Writing Tests?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Writing Tests com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Writing Tests é gratuita?

A habilidade é publicada no GitHub por NTCoding. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇