Skip to content

Documentation: Using $derived rune in tests #15405

@TenCoKaciStromy

Description

@TenCoKaciStromy

Describe the problem

I run in problem with using $derived rune in test.

describe("lab", () => {
  it("can use $derived", () => {
    let firstName = $state<string>()
    let lastName = $state<string>()
    const fullName = $derived([firstName, lastName].join("+"))

    expect(fullName).toBe("+")

    firstName = "Alice"
    expect(fullName).toBe("Alice")
  })
})

The problem was, the code was not wrapped by $effect.root(() => { ... })().

The documentation for testing contains part for Using runes inside your test files with explanation about $effect, but as newbee I din't realize, that $derived is $effect.

Describe the proposed solution

I propose to add the example with test using $derived rune, explaining the $derived is actually $effect.

it("can use $derived", () => {
  $effect.root(() => {
    let firstName = $state<string>()
    let lastName = $state<string>()
    // because of $derived, the code must be wrapped by $effect.root(...)
    const fullName = $derived([firstName, lastName].join("+"))
    expect(fullName).toBe("+")

    firstName = "Alice"
    expect(fullName).toBe("Alice+")
  })()
})

Importance

nice to have

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions