Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active September 28, 2023 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trikitrok/fd74d5ac99f45a41152045775c8317b1 to your computer and use it in GitHub Desktop.
Save trikitrok/fd74d5ac99f45a41152045775c8317b1 to your computer and use it in GitHub Desktop.

Tools

Example of spying an interaction

interface Collaborator {
    collaborate(): void;
}

class MyClass {
    private collaborator: Collaborator;
    
    constructor(collaborator: Collaborator) {
        this.collaborator = collaborator;
    }

    run(): void {
        this.collaborator.collaborate();
    }
}

test('example of a spying an interaction', () => {
    const collaborator = mock<Collaborator>();
    const myClass = new MyClass(instance(collaborator));

    myClass.run();

    verify(collaborator.collaborate()).once();
});

Example of stubbing an interaction

interface Collaborator {
    collaborate(): string;
}

class MyClass {
    private collaborator: Collaborator;
    
    constructor(collaborator: Collaborator) {
        this.collaborator = collaborator;
    }

    run(): void {
        return this.collaborator.collaborate();
    }
}

test('example of a stubbing an interaction', () => {
    const collaboratorResponse = "some response";
    const collaborator = mock<Collaborator>();
    when(collaborator.collaborate()).thenReturn(collaboratorResponse);
    const myClass = new MyClass(instance(collaborator));

    const result = myClass.run();

    expect(result).toBe(collaboratorResponse);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment