Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support Deno.beforeEach to run a function before each of the tests #10741

Closed

Conversation

getspooky
Copy link
Contributor

@getspooky getspooky commented May 21, 2021

Description

Runs a function before each of the tests in this file runs. If the function returns a promise, Deno waits for that promise to resolve before running the test.

Deno.beforeEach(function(): void {
  // 
});
Deno.test("Hello Test", () => {
  assert("Hello");
});

Motivation

Most times you have setup work that has to happen before the tests run. For example consider when you have several tests interact with a database of cities. You have a method initializeCityDatabase() that has to be called before each of these tests
Deno provides helper functions Deno.beforeEach to handle this.

beforeEach(() => {
  initializeCityDatabase();
});

Deno.test("city database has Casablanca", () => {
  assert(isCity("Casablanca"));
});

@caspervonb
Copy link
Contributor

caspervonb commented May 22, 2021

Let me preface this with saying that I appreciate the effort, but...

I am very strongly against sticking this in the test runner.
It is preferable to use composition instead.

Deno.test("myTestWithdatabase", withDatabase(async function(db) {
  // ...
});

Global hooks encourages global state, which is a mistake.
I don't intend us to hop on the bad design bandwagon just because other testing frameworks in JavaScript has done it in the past.

You're better off using helper functions that to do the specific setup and teardown that you need for you and provide you with a closure that has the required state as this can be factored into a test_helper module be re-used, composed, etc.

If you really want to use global state hooks you can do something like this:

import { beforeEach, afterEach, withHooks } from "./test_util.ts";

beforeEach(async function() {
});

afterEach(async function() {
});

Deno.test("", withHooks(async function() {
});

@ry
Copy link
Member

ry commented May 22, 2021

Thanks @getspooky - but I'm in agreement with Casper.

Maybe we need some better documentation or even a helper module in std/testing/ to communicate this pattern more effectively.

Closing without merge.

@ry
Copy link
Member

ry commented May 22, 2021

I've opened an issue in std for adding a utility library for this functionality
denoland/std#931

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants