---
description: Reuse tests across contexts with `this`
title: Shared Behaviours
---

Mocha currently has no concept of a "shared behaviour" however the "contexts" facilitate this feature. For example suppose you have an `Admin` which inherits from `User`, you most likely will not want to duplicate the `User` tests for `Admin`. The "context" (`this`) is the same object within the "before each", "after each" hooks, and the test-case itself, allowing you to utilize this instead of closures to store data. The following is an example of how you can achieve this sort of functionality:

shared.js:

```js
export function shouldBehaveLikeAUser() {
  it("should have .name.first", function () {
    this.user.name.first.should.equal("tobi");
  });

  it("should have .name.last", function () {
    this.user.name.last.should.equal("holowaychuk");
  });

  describe(".fullname()", function () {
    it("should return the full name", function () {
      this.user.fullname().should.equal("tobi holowaychuk");
    });
  });
}
```

test.js:

```js
import { User, Admin } from "./user.js";
import { shouldBehaveLikeAUser } from "./shared.js";

describe("User", function () {
  beforeEach(function () {
    this.user = new User("tobi", "holowaychuk");
  });

  shouldBehaveLikeAUser();
});

describe("Admin", function () {
  beforeEach(function () {
    this.user = new Admin("tobi", "holowaychuk");
  });

  shouldBehaveLikeAUser();

  it("should be an .admin", function () {
    this.user.admin.should.be.true;
  });
});
```

user.js:

```js
export class User {
  constructor(first, last) {
    this.name = {
      first: first,
      last: last,
    };
  }

  fullname() {
    return this.name.first + " " + this.name.last;
  }
}

export class Admin extends User {
  constructor(first, last) {
    super(first, last);
    this.admin = true;
  }
}
```
