ecmascript 6 - Unit tests isolation with jestjs -
what best way handle test isolation jest? want test es6 class static methods , mock methods not directly concerned unit test.
my class file :
class util { static getfirstname() { return "john"; } static getlastname() { return "doe"; } static getfullname(){ return `${util.getfirstname()} ${util.getlastname()}`; } }
my test file :
import util '../src/util'; test("test getfullname", () => { util.getfirstname = jest.fn().mockreturnvalue("mockfirstname"); util.getlastname = jest.fn().mockreturnvalue("mocklastname"); expect(util.getfullname()).tobe("mockfirstname mocklastname") }); test("test getfirstname", () => { expect(util.getfirstname()).tobe("john") }); test("test getlastname", () => { expect(util.getlastname()).tobe("doe") });
this way, 2 last tests fail because mocks set on first test still active.
assuming import
statements being transpiled require
, should able use resetmodules:
beforeeach(() => { // clears require cache new module require'd // before each test. jest.resetmodules(); });
then in each test, you'll need require module:
test("name", () => { const { default: util } = require("../src/util"); });
or if can use dynamic import syntax:
test("name", () => import("../src/util") .then(({ default: util }) => { expect(util.getfirstname()).tobe("john"); }) );
Comments
Post a Comment