[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D28ETEQGAE1W24KJGD6DW6":3,"skill-same:01M6D28ETEQGAE1W24KJGD6DW6":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":47,"ownerHtmlUrl":48,"ownerBlogUrl":47,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M6D28ETEQGAE1W24KJGD6DW6","testing-unit",null,"Unit tests for logic: finding the cases (empty, one, many, boundaries, invalid, Unicode, time zones, large inputs), table-driven and parameterised tests, test doubles (fakes before mocks, mocks only at boundaries), property-based testing for invariants, careful snapshots, and the idioms of each language's test framework. Read before writing unit tests.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Ftesting-unit\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"testing unit","testing","only","tests","logic","empty","time","language","snapshots","idioms","read","table","careful","framework","test framework","unit tests","test","writing","2026-11-10 10:12:30",false,"---\nname: testing-unit\ndescription: \"Unit tests for logic: finding the cases (empty, one, many, boundaries, invalid, Unicode, time zones, large inputs), table-driven and parameterised tests, test doubles (fakes before mocks, mocks only at boundaries), property-based testing for invariants, careful snapshots, and the idioms of each language's test framework. Read before writing unit tests.\"\n---\n\n# Unit tests for logic\n\nGenerated unit tests have one happy-path case per function, a mock for every\ncollaborator, `expect(result).toBeTruthy()` and names like `test_calculate`.\nThey pass while the logic is wrong at the edges (the empty list, the last\npage, the leap day), which is where the bugs are. This skill finds the\ncases, writes them as tables, chooses doubles, adds properties, and gives\neach language's idioms. Principles are in `testing`.\n\n## 1. What a unit is\n\n- A behaviour, not a class or a file: one public function, or a few objects\n  that together do one thing, tested through the public API.\n- Pure logic is the target. Time, randomness, I\u002FO and configuration are\n  passed in (`code`: side effects at the edges). Code that is hard to unit\n  test usually mixes a decision with I\u002FO: split it.\n- In process, in milliseconds: no network, database or container; files only\n  in a temporary directory (`tmp_path`, `t.TempDir()`).\n\n## 2. Finding the cases\n\nGo through the list for every input; most bugs sit in the first rows.\n\n| Kind | Cases |\n|---|---|\n| Empty and missing | `\"\"`, whitespace only, `[]`, `{}`, `null`\u002F`None`\u002F`nil`, an optional field absent |\n| One and many | one item, two (the first interaction), many (1,000 or more) |\n| Boundaries | at, below and above each limit: 0, 1, limit minus 1, limit, limit plus 1; first and last index; a page exactly full; inclusive against exclusive ranges |\n| Sign and zero | negative, zero, `-0` (`Object.is(-0, 0)` is false) |\n| Size and precision | integer overflow; `Number.MAX_SAFE_INTEGER + 1`; `0.1 + 0.2 !== 0.3`; rounding a half (banker's or half up); division by zero; `NaN` |\n| Invalid formats | malformed email, `2026-02-30` (in V8, `new Date(\"2026-02-30\")` quietly becomes 2 March), `1,5` against `1.5`, truncated JSON, wrong types, extra fields |\n| Unicode | composed `\"\\u00e9\"` against decomposed `\"e\\u0301\"` (unequal until normalised to NFC); `\"\\u{1F469}\\u200D\\u{1F469}\\u200D\\u{1F467}\"` is 1 grapheme, 5 code points, 8 UTF-16 units; truncation that splits a pair; Turkish `\"I\".toLocaleLowerCase(\"tr\")` is `\"ı\"`; `\"ß\".toUpperCase()` is `\"SS\"`; right-to-left text; non-breaking and zero-width spaces |\n| Time zones and DST | a local day of 23 hours (2026-03-29 in Europe\u002FLondon, 2026-03-08 in America\u002FNew_York) or 25 (2026-10-25, 2026-11-01); a local time that does not exist or happens twice; offsets of +05:30 and +05:45; midnight UTC being the previous day in the Americas |\n| Calendar | 29 February (2028; 1900 was not a leap year, 2000 was); 31 January plus one month; year end; ISO week 53 (2026-12-31 and 2027-01-01 are both in week 53 of 2026) |\n| Locale | `1.234,56` in de-DE and id-ID; `03\u002F04` as March or April; collation of accented letters; plural forms |\n| Large inputs | a 1 MB string, 100,000 items (quadratic code shows), deep nesting |\n| Duplicates and order | equal keys, equal timestamps, stable sorting, results compared ignoring order when order is not promised |\n| State | called twice (idempotent?), called out of order, after an error |\n| Errors | every documented error, checked by type or code, not only \"it throws\" |\n\n## 3. Tables of cases\n\nWhen cases share one shape, list them as data, each with a name, so a\nfailure names the case and adding one is a line.\n\n```go\nfunc TestParseAmount(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tin      string\n\t\twant    int64\n\t\twantErr bool\n\t}{\n\t\t{name: \"whole units\", in: \"12\", want: 1200},\n\t\t{name: \"two decimals\", in: \"12.34\", want: 1234},\n\t\t{name: \"empty\", in: \"\", wantErr: true},\n\t\t{name: \"three decimals\", in: \"1.234\", wantErr: true},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := ParseAmount(tt.in)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Fatalf(\"ParseAmount(%q) error = %v, wantErr %v\", tt.in, err, tt.wantErr)\n\t\t\t}\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"ParseAmount(%q) = %d, want %d\", tt.in, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n```\n\nRun one case: `go test -run 'TestParseAmount\u002Fthree_decimals'` (spaces become\nunderscores). No `tt := tt` since Go 1.22.\n\n```python\n@pytest.mark.parametrize(\n    (\"raw\", \"cents\"),\n    [\n        pytest.param(\"12\", 1200, id=\"whole units\"),\n        pytest.param(\"12.34\", 1234, id=\"two decimals\"),\n    ],\n)\ndef test_parse_amount(raw, cents):\n    assert parse_amount(raw) == cents\n\n\n@pytest.mark.parametrize(\"raw\", [\"\", \"1.234\", \"-1\", \"1,5\"])\ndef test_parse_amount_rejects(raw):\n    with pytest.raises(InvalidAmount):\n        parse_amount(raw)\n```\n\n```ts\nit.each([\n  { raw: \"12\", cents: 1200 },\n  { raw: \"12.34\", cents: 1234 },\n])(\"parses $raw as $cents cents\", ({ raw, cents }) => {\n  expect(parseAmount(raw)).toBe(cents);\n});\n```\n\n```rust\n#[rstest]\n#[case::whole_units(\"12\", 1200)]\n#[case::two_decimals(\"12.34\", 1234)]\nfn parses_amounts(#[case] raw: &str, #[case] cents: i64) {\n    assert_eq!(parse_amount(raw).unwrap(), cents);\n}\n```\n\nAlso: JUnit `@ParameterizedTest` with `@CsvSource`, xUnit `[Theory]` with\n`[InlineData]`, Pest `->with([...])`. Outside Go, successes and failures go\nin separate tables.\n\n## 4. Test doubles\n\n| Double | What it is | Use it for |\n|---|---|---|\n| Dummy | fills a parameter, never used | a required argument |\n| Stub | returns canned answers | inputs from a dependency (a rate, a user) |\n| Fake | a small working implementation (in-memory repository, fake clock) | stateful dependencies: the default |\n| Spy | records calls | checking an output that is the behaviour (the email sent) |\n| Mock | expectations set in advance and verified | rarely, at a boundary where the call is the contract |\n\n- Use the real thing for your own pure code: never mock a value object, a\n  mapper or a calculation.\n- Fakes of your own interfaces before mocks. A mock encodes the call\n  sequence and breaks on refactors; a fake behaves like the real thing.\n  Run one shared contract test suite against the fake and the real\n  implementation so they cannot drift.\n- Replace only what crosses a boundary you own: your `PaymentGateway`,\n  `Clock`, `Mailer` interfaces.\n- Never mock what you do not own (an SDK, `fetch`, `requests`, the ORM):\n  wrap it in a small adapter you own, fake the adapter in unit tests, and\n  test the adapter against a faked HTTP edge (`testing-integration`).\n- Assert on state before interactions: the order is saved as paid, not\n  `save` was called. Verify a call only when the call is the outcome, and\n  then check its arguments exactly.\n- Keep doubles strict, so a misspelt or unexpected call fails:\n  `create_autospec(Class, instance=True, spec_set=True)` in Python, Mockito's\n  strict stubs with `MockitoExtension`, `instance_double` in RSpec,\n  `mockall` expectations in Rust.\n\n```ts\nit(\"expires a reservation after 15 minutes\", () => {\n  let now = new Date(\"2026-09-29T10:00:00Z\");\n  const reservations = new Reservations({ current: () => now }); \u002F\u002F a fake Clock\n  const r = reservations.hold(\"seat-12\");\n\n  now = new Date(\"2026-09-29T10:15:00Z\");\n\n  expect(reservations.isActive(r.id)).toBe(false);\n});\n```\n\n## 5. Property-based tests\n\nFor invariants over many inputs: round trips (`parse(format(x)) == x`),\nidempotence (`slug(slug(s)) == slug(s)`), invariants (a sort's output is\nordered and a permutation), a fast implementation against a slow obvious\none. Examples still pin the business rules; properties add the inputs\nnobody thought of, shrunk to a minimal case with a seed to replay.\n\n```ts\nit(\"sorts any list of numbers without losing items\", () => {\n  fc.assert(\n    fc.property(fc.array(fc.integer()), (xs) => {\n      const sorted = sortNumbers(xs);\n      expect(sorted).toHaveLength(xs.length);\n      for (let i = 1; i \u003C sorted.length; i++) expect(sorted[i - 1]).toBeLessThanOrEqual(sorted[i]);\n    }),\n  );\n});\n```\n\nThat property catches `xs.sort()` without a comparator (JavaScript sorts\nnumbers as strings) within a few runs and shrinks it to two numbers.\n\n```python\n@given(st.text())\n@example(\"  Hello  World \")\ndef test_slug_is_idempotent(s):\n    assert slugify(slugify(s)) == slugify(s)\n```\n\n- Tools: fast-check (`@fast-check\u002Fvitest` adds `test.prop`), Hypothesis,\n  proptest (`proptest! { #[test] fn f(c in 0i64..=1_000_000) { ... } }`),\n  rapid for Go, jqwik for Java, FsCheck for .NET. Most run 100 cases by\n  default (proptest 256, jqwik 1,000): enough per commit; more nightly.\n- Go's native fuzzing does the same for bytes and strings:\n  `go test -fuzz=FuzzParseAmount -fuzztime=30s .\u002Fmoney`. Failing inputs are\n  saved under `testdata\u002Ffuzz\u002F` and rerun by plain `go test`: commit them. A\n  round-trip fuzz target finds an `int64` overflow in `whole*100` in seconds.\n- Keep every counterexample found: `@example(...)` in Hypothesis, a fixed\n  case in the table, proptest's `proptest-regressions\u002F` files committed.\n- Constrain generators to valid domains: `fc.date({ noInvalidDate: true })`\n  (the default can produce `Invalid Date`), `st.decimals(places=2,\n  allow_nan=False)`.\n\n## 6. Snapshots, carefully\n\n- Only for small, stable, reviewed output (an error message, generated SQL,\n  a CLI's help), never whole responses, large trees, timestamps or ids.\n- Inline snapshots keep the expected value where the reviewer reads it:\n  `toMatchInlineSnapshot()`, `insta::assert_snapshot!(v, @\"...\")`.\n- Redact volatile fields: `toMatchSnapshot({ id: expect.any(String) })`;\n  insta `assert_json_snapshot!(order, { \".id\" => \"[id]\" })`.\n- An update is a change to review line by line (`vitest -u`, `jest -u`,\n  `cargo insta review`, `pytest --snapshot-update` with syrupy), never a way\n  to make the build green. In CI missing snapshots fail instead of being\n  written (Vitest when `CI` is set, Jest with `--ci`, insta by default).\n\n## 7. Assertions and names\n\n- The most specific matcher: `toEqual` for structures, `containsExactly` in\n  AssertJ, `assert_eq!`, pytest's plain `assert` (it shows a diff).\n- Messages that say what went wrong: `t.Errorf(\"Total(%v) = %d, want %d\",\n  items, got, want)`; `cmp.Diff(want, got)` from go-cmp for structs.\n- Floats compared with a tolerance (`toBeCloseTo`, `pytest.approx`,\n  `isCloseTo(x, within(1e-9))`); money never as a float.\n- Errors by type or code: `toThrow(InvalidAmount)`,\n  `pytest.raises(InvalidAmount, match=\"decimals\")`, `errors.Is(err,\n  ErrInvalid)`, `assert!(matches!(e, ParseError::TooPrecise))`.\n- A name is the behaviour in a sentence: `rejects_more_than_two_decimals`,\n  `it(\"rejects more than two decimals\")`, JUnit `@DisplayName`.\n\n## 8. Per-language notes\n\n- **Vitest and Jest**: `restoreMocks: true` in config; `vi.useFakeTimers()`\n  with `vi.setSystemTime()`, real timers again in `afterEach`; always\n  `await` or return promises (`await expect(p).rejects.toThrow()`); injected\n  dependencies over hoisted `vi.mock()` module mocks.\n- **pytest**: fixtures in `conftest.py` at the narrowest scope; `tmp_path`,\n  `monkeypatch`, `caplog`; the `subtests` fixture is built in from pytest 9;\n  markers registered and `--strict-markers`.\n- **Go**: `t.Helper()` in helpers; `t.Cleanup`, `t.TempDir()`, `t.Setenv`\n  (not with `t.Parallel()`), `t.Context()` (1.24); `testing\u002Fsynctest` (1.25)\n  runs timers and goroutines on a fake clock; `Example` functions with\n  `\u002F\u002F Output:` are tested docs. With testify: `require` for preconditions,\n  `assert` for checks, and the `(t, expected, actual)` order.\n- **Rust**: `#[cfg(test)] mod tests` beside the code, `tests\u002F` for the public\n  API; tests may return `Result` and use `?`; `#[should_panic(expected =\n  \"...\")]` only when panicking is the contract; `cargo test --doc` runs doc\n  examples; `mockall` for traits you own.\n- **JUnit 5 or 6 with AssertJ**: `@Nested` classes per situation,\n  `@ParameterizedTest`, `@TempDir`, Mockito with `MockitoExtension`, jqwik\n  `@Property`. JUnit 6 needs Java 17.\n- **xUnit**: `[Fact]`, `[Theory]`; constructor for setup, `IDisposable` for\n  teardown; `FakeTimeProvider` for time. FluentAssertions 8 and later need a\n  paid licence for commercial use; AwesomeAssertions (a fork) and Shouldly\n  are free. Keep what the project uses.\n- **RSpec, Minitest, PHPUnit, Pest**: `context \"when ...\"` blocks and `let`;\n  `expect { }.to change { Order.count }.by(1)`; Minitest runs in random\n  order and prints its seed; PHPUnit attributes `#[Test]`,\n  `#[DataProvider]`; Pest `->throws(InvalidAmount::class)`.\n\n## Check it\n\n- Break the logic on purpose (flip `\u003C`, drop a branch): a new test fails.\n  Or run a mutation tool on the file (`testing`, section 5).\n- The cases cover the rows of section 2 that apply; say which were left out.\n- The file passes alone, in the full suite and in random order.\n- A property test's failure output shows a seed you can replay.\n\n## Avoid\n\nOne happy-path case per function; mocking the unit's own pure\ncollaborators; mocking libraries you do not own; assertions on call order\nor private state; `toBeTruthy()` where the value is known; expected values\ncomputed by the code under test; floats for money; large snapshots; the\nreal clock, `Math.random`, environment or network inside a unit test;\n`sleep`; property tests without the example cases for the rules.\n","# Unit tests for logic\n\nGenerated unit tests have one happy-path case per function, a mock for every\ncollaborator, `expect(result).toBeTruthy()` and names like `test_calculate`.\nThey pass while the logic is wrong at the edges (the empty list, the last\npage, the leap day), which is where the bugs are. This skill finds the\ncases, writes them as tables, chooses doubles, adds properties, and gives\neach language's idioms. Principles are in `testing`.\n\n## 1. What a unit is\n\n- A behaviour, not a class or a file: one public function, or a few objects\n  that together do one thing, tested through the public API.\n- Pure logic is the target. Time, randomness, I\u002FO and configuration are\n  passed in (`code`: side effects at the edges). Code that is hard to unit\n  test usually mixes a decision with I\u002FO: split it.\n- In process, in milliseconds: no network, database or container; files only\n  in a temporary directory (`tmp_path`, `t.TempDir()`).\n\n## 2. Finding the cases\n\nGo through the list for every input; most bugs sit in the first rows.\n\n| Kind | Cases |\n|---|---|\n| Empty and missing | `\"\"`, whitespace only, `[]`, `{}`, `null`\u002F`None`\u002F`nil`, an optional field absent |\n| One and many | one item, two (the first interaction), many (1,000 or more) |\n| Boundaries | at, below and above each limit: 0, 1, limit minus 1, limit, limit plus 1; first and last index; a page exactly full; inclusive against exclusive ranges |\n| Sign and zero | negative, zero, `-0` (`Object.is(-0, 0)` is false) |\n| Size and precision | integer overflow; `Number.MAX_SAFE_INTEGER + 1`; `0.1 + 0.2 !== 0.3`; rounding a half (banker's or half up); division by zero; `NaN` |\n| Invalid formats | malformed email, `2026-02-30` (in V8, `new Date(\"2026-02-30\")` quietly becomes 2 March), `1,5` against `1.5`, truncated JSON, wrong types, extra fields |\n| Unicode | composed `\"\\u00e9\"` against decomposed `\"e\\u0301\"` (unequal until normalised to NFC); `\"\\u{1F469}\\u200D\\u{1F469}\\u200D\\u{1F467}\"` is 1 grapheme, 5 code points, 8 UTF-16 units; truncation that splits a pair; Turkish `\"I\".toLocaleLowerCase(\"tr\")` is `\"ı\"`; `\"ß\".toUpperCase()` is `\"SS\"`; right-to-left text; non-breaking and zero-width spaces |\n| Time zones and DST | a local day of 23 hours (2026-03-29 in Europe\u002FLondon, 2026-03-08 in America\u002FNew_York) or 25 (2026-10-25, 2026-11-01); a local time that does not exist or happens twice; offsets of +05:30 and +05:45; midnight UTC being the previous day in the Americas |\n| Calendar | 29 February (2028; 1900 was not a leap year, 2000 was); 31 January plus one month; year end; ISO week 53 (2026-12-31 and 2027-01-01 are both in week 53 of 2026) |\n| Locale | `1.234,56` in de-DE and id-ID; `03\u002F04` as March or April; collation of accented letters; plural forms |\n| Large inputs | a 1 MB string, 100,000 items (quadratic code shows), deep nesting |\n| Duplicates and order | equal keys, equal timestamps, stable sorting, results compared ignoring order when order is not promised |\n| State | called twice (idempotent?), called out of order, after an error |\n| Errors | every documented error, checked by type or code, not only \"it throws\" |\n\n## 3. Tables of cases\n\nWhen cases share one shape, list them as data, each with a name, so a\nfailure names the case and adding one is a line.\n\n```go\nfunc TestParseAmount(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tin      string\n\t\twant    int64\n\t\twantErr bool\n\t}{\n\t\t{name: \"whole units\", in: \"12\", want: 1200},\n\t\t{name: \"two decimals\", in: \"12.34\", want: 1234},\n\t\t{name: \"empty\", in: \"\", wantErr: true},\n\t\t{name: \"three decimals\", in: \"1.234\", wantErr: true},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := ParseAmount(tt.in)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Fatalf(\"ParseAmount(%q) error = %v, wantErr %v\", tt.in, err, tt.wantErr)\n\t\t\t}\n\t\t\tif got != tt.want {\n\t\t\t\tt.Errorf(\"ParseAmount(%q) = %d, want %d\", tt.in, got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n```\n\nRun one case: `go test -run 'TestParseAmount\u002Fthree_decimals'` (spaces become\nunderscores). No `tt := tt` since Go 1.22.\n\n```python\n@pytest.mark.parametrize(\n    (\"raw\", \"cents\"),\n    [\n        pytest.param(\"12\", 1200, id=\"whole units\"),\n        pytest.param(\"12.34\", 1234, id=\"two decimals\"),\n    ],\n)\ndef test_parse_amount(raw, cents):\n    assert parse_amount(raw) == cents\n\n\n@pytest.mark.parametrize(\"raw\", [\"\", \"1.234\", \"-1\", \"1,5\"])\ndef test_parse_amount_rejects(raw):\n    with pytest.raises(InvalidAmount):\n        parse_amount(raw)\n```\n\n```ts\nit.each([\n  { raw: \"12\", cents: 1200 },\n  { raw: \"12.34\", cents: 1234 },\n])(\"parses $raw as $cents cents\", ({ raw, cents }) => {\n  expect(parseAmount(raw)).toBe(cents);\n});\n```\n\n```rust\n#[rstest]\n#[case::whole_units(\"12\", 1200)]\n#[case::two_decimals(\"12.34\", 1234)]\nfn parses_amounts(#[case] raw: &str, #[case] cents: i64) {\n    assert_eq!(parse_amount(raw).unwrap(), cents);\n}\n```\n\nAlso: JUnit `@ParameterizedTest` with `@CsvSource`, xUnit `[Theory]` with\n`[InlineData]`, Pest `->with([...])`. Outside Go, successes and failures go\nin separate tables.\n\n## 4. Test doubles\n\n| Double | What it is | Use it for |\n|---|---|---|\n| Dummy | fills a parameter, never used | a required argument |\n| Stub | returns canned answers | inputs from a dependency (a rate, a user) |\n| Fake | a small working implementation (in-memory repository, fake clock) | stateful dependencies: the default |\n| Spy | records calls | checking an output that is the behaviour (the email sent) |\n| Mock | expectations set in advance and verified | rarely, at a boundary where the call is the contract |\n\n- Use the real thing for your own pure code: never mock a value object, a\n  mapper or a calculation.\n- Fakes of your own interfaces before mocks. A mock encodes the call\n  sequence and breaks on refactors; a fake behaves like the real thing.\n  Run one shared contract test suite against the fake and the real\n  implementation so they cannot drift.\n- Replace only what crosses a boundary you own: your `PaymentGateway`,\n  `Clock`, `Mailer` interfaces.\n- Never mock what you do not own (an SDK, `fetch`, `requests`, the ORM):\n  wrap it in a small adapter you own, fake the adapter in unit tests, and\n  test the adapter against a faked HTTP edge (`testing-integration`).\n- Assert on state before interactions: the order is saved as paid, not\n  `save` was called. Verify a call only when the call is the outcome, and\n  then check its arguments exactly.\n- Keep doubles strict, so a misspelt or unexpected call fails:\n  `create_autospec(Class, instance=True, spec_set=True)` in Python, Mockito's\n  strict stubs with `MockitoExtension`, `instance_double` in RSpec,\n  `mockall` expectations in Rust.\n\n```ts\nit(\"expires a reservation after 15 minutes\", () => {\n  let now = new Date(\"2026-09-29T10:00:00Z\");\n  const reservations = new Reservations({ current: () => now }); \u002F\u002F a fake Clock\n  const r = reservations.hold(\"seat-12\");\n\n  now = new Date(\"2026-09-29T10:15:00Z\");\n\n  expect(reservations.isActive(r.id)).toBe(false);\n});\n```\n\n## 5. Property-based tests\n\nFor invariants over many inputs: round trips (`parse(format(x)) == x`),\nidempotence (`slug(slug(s)) == slug(s)`), invariants (a sort's output is\nordered and a permutation), a fast implementation against a slow obvious\none. Examples still pin the business rules; properties add the inputs\nnobody thought of, shrunk to a minimal case with a seed to replay.\n\n```ts\nit(\"sorts any list of numbers without losing items\", () => {\n  fc.assert(\n    fc.property(fc.array(fc.integer()), (xs) => {\n      const sorted = sortNumbers(xs);\n      expect(sorted).toHaveLength(xs.length);\n      for (let i = 1; i \u003C sorted.length; i++) expect(sorted[i - 1]).toBeLessThanOrEqual(sorted[i]);\n    }),\n  );\n});\n```\n\nThat property catches `xs.sort()` without a comparator (JavaScript sorts\nnumbers as strings) within a few runs and shrinks it to two numbers.\n\n```python\n@given(st.text())\n@example(\"  Hello  World \")\ndef test_slug_is_idempotent(s):\n    assert slugify(slugify(s)) == slugify(s)\n```\n\n- Tools: fast-check (`@fast-check\u002Fvitest` adds `test.prop`), Hypothesis,\n  proptest (`proptest! { #[test] fn f(c in 0i64..=1_000_000) { ... } }`),\n  rapid for Go, jqwik for Java, FsCheck for .NET. Most run 100 cases by\n  default (proptest 256, jqwik 1,000): enough per commit; more nightly.\n- Go's native fuzzing does the same for bytes and strings:\n  `go test -fuzz=FuzzParseAmount -fuzztime=30s .\u002Fmoney`. Failing inputs are\n  saved under `testdata\u002Ffuzz\u002F` and rerun by plain `go test`: commit them. A\n  round-trip fuzz target finds an `int64` overflow in `whole*100` in seconds.\n- Keep every counterexample found: `@example(...)` in Hypothesis, a fixed\n  case in the table, proptest's `proptest-regressions\u002F` files committed.\n- Constrain generators to valid domains: `fc.date({ noInvalidDate: true })`\n  (the default can produce `Invalid Date`), `st.decimals(places=2,\n  allow_nan=False)`.\n\n## 6. Snapshots, carefully\n\n- Only for small, stable, reviewed output (an error message, generated SQL,\n  a CLI's help), never whole responses, large trees, timestamps or ids.\n- Inline snapshots keep the expected value where the reviewer reads it:\n  `toMatchInlineSnapshot()`, `insta::assert_snapshot!(v, @\"...\")`.\n- Redact volatile fields: `toMatchSnapshot({ id: expect.any(String) })`;\n  insta `assert_json_snapshot!(order, { \".id\" => \"[id]\" })`.\n- An update is a change to review line by line (`vitest -u`, `jest -u`,\n  `cargo insta review`, `pytest --snapshot-update` with syrupy), never a way\n  to make the build green. In CI missing snapshots fail instead of being\n  written (Vitest when `CI` is set, Jest with `--ci`, insta by default).\n\n## 7. Assertions and names\n\n- The most specific matcher: `toEqual` for structures, `containsExactly` in\n  AssertJ, `assert_eq!`, pytest's plain `assert` (it shows a diff).\n- Messages that say what went wrong: `t.Errorf(\"Total(%v) = %d, want %d\",\n  items, got, want)`; `cmp.Diff(want, got)` from go-cmp for structs.\n- Floats compared with a tolerance (`toBeCloseTo`, `pytest.approx`,\n  `isCloseTo(x, within(1e-9))`); money never as a float.\n- Errors by type or code: `toThrow(InvalidAmount)`,\n  `pytest.raises(InvalidAmount, match=\"decimals\")`, `errors.Is(err,\n  ErrInvalid)`, `assert!(matches!(e, ParseError::TooPrecise))`.\n- A name is the behaviour in a sentence: `rejects_more_than_two_decimals`,\n  `it(\"rejects more than two decimals\")`, JUnit `@DisplayName`.\n\n## 8. Per-language notes\n\n- **Vitest and Jest**: `restoreMocks: true` in config; `vi.useFakeTimers()`\n  with `vi.setSystemTime()`, real timers again in `afterEach`; always\n  `await` or return promises (`await expect(p).rejects.toThrow()`); injected\n  dependencies over hoisted `vi.mock()` module mocks.\n- **pytest**: fixtures in `conftest.py` at the narrowest scope; `tmp_path`,\n  `monkeypatch`, `caplog`; the `subtests` fixture is built in from pytest 9;\n  markers registered and `--strict-markers`.\n- **Go**: `t.Helper()` in helpers; `t.Cleanup`, `t.TempDir()`, `t.Setenv`\n  (not with `t.Parallel()`), `t.Context()` (1.24); `testing\u002Fsynctest` (1.25)\n  runs timers and goroutines on a fake clock; `Example` functions with\n  `\u002F\u002F Output:` are tested docs. With testify: `require` for preconditions,\n  `assert` for checks, and the `(t, expected, actual)` order.\n- **Rust**: `#[cfg(test)] mod tests` beside the code, `tests\u002F` for the public\n  API; tests may return `Result` and use `?`; `#[should_panic(expected =\n  \"...\")]` only when panicking is the contract; `cargo test --doc` runs doc\n  examples; `mockall` for traits you own.\n- **JUnit 5 or 6 with AssertJ**: `@Nested` classes per situation,\n  `@ParameterizedTest`, `@TempDir`, Mockito with `MockitoExtension`, jqwik\n  `@Property`. JUnit 6 needs Java 17.\n- **xUnit**: `[Fact]`, `[Theory]`; constructor for setup, `IDisposable` for\n  teardown; `FakeTimeProvider` for time. FluentAssertions 8 and later need a\n  paid licence for commercial use; AwesomeAssertions (a fork) and Shouldly\n  are free. Keep what the project uses.\n- **RSpec, Minitest, PHPUnit, Pest**: `context \"when ...\"` blocks and `let`;\n  `expect { }.to change { Order.count }.by(1)`; Minitest runs in random\n  order and prints its seed; PHPUnit attributes `#[Test]`,\n  `#[DataProvider]`; Pest `->throws(InvalidAmount::class)`.\n\n## Check it\n\n- Break the logic on purpose (flip `\u003C`, drop a branch): a new test fails.\n  Or run a mutation tool on the file (`testing`, section 5).\n- The cases cover the rows of section 2 that apply; say which were left out.\n- The file passes alone, in the full suite and in random order.\n- A property test's failure output shows a seed you can replay.\n\n## Avoid\n\nOne happy-path case per function; mocking the unit's own pure\ncollaborators; mocking libraries you do not own; assertions on call order\nor private state; `toBeTruthy()` where the value is known; expected values\ncomputed by the code under test; floats for money; large snapshots; the\nreal clock, `Math.random`, environment or network inside a unit test;\n`sleep`; property tests without the example cases for the rules.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Ftesting-unit",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add enowdev\u002Fenowxcli --skill testing-unit",{"tool":57,"command":58},"bunx","bunx skills add enowdev\u002Fenowxcli --skill testing-unit",{"tool":60,"command":61},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill testing-unit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Ftesting-unit\u002FSKILL.md",true,[65,71,77],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002FInvoke-PortalSearchNav.ps1","SCRIPT","脚本",9812,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Faks-skills\u002Fskills\u002Fazure-search-nav\u002Freferences\u002FInvoke-PortalSearchNav.ps1",{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002FREADME.md","REFERENCE","参考文档",3867,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Faks-skills\u002Fskills\u002Fazure-search-nav\u002Freferences\u002FREADME.md",{"path":78,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fresource-types.json",4418,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fskills\u002Fblob\u002Fmain\u002F.github\u002Fplugins\u002Faks-skills\u002Fskills\u002Fazure-search-nav\u002Freferences\u002Fresource-types.json",[82,92,107,120,141,160],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":37},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[],[89,90,22,91,29],"demo skill","demo","project",{"skillNo":93,"name":36,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":37},"01M6D2HM0GCPM0TM2HPG9HHR2R","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[],[36,98,99,24,100,101,29,102,103,104,105,106],"text","emails","drop","document","page","voice","notifications","documentation","translate",{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":37},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[],[109,114,115,116,117,102,118,29,119],"icons","components","SET","responsive","layout","before building",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":37},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[],[109,127,128,129,130,131,132,133,134,29,119,135,102,136,137,138,114,139,140],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","code","Charts","content","screenshots","logo",{"skillNo":142,"name":143,"nameZh":6,"description":144,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":145,"categories":146,"keywords":147,"publishedAt":37},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[],[148,109,149,115,150,151,136,152,153,154,118,130,155,156,157,29,119,102,158,159],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":37},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[],[109,167,168,169,170,171,172,173,118,91,174,175,29,176,177,178,179,180,181,20],"vue","stack","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","config","directory"]