Setup and Teardown
테스트가 실행 전, 후로 수행해야 하는 일을 설정 합니다.
반복적인으로 setup 할 경우
javascript
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test("city database has Vienna", () => {
expect(isCity("Vienna")).toBeTruthy();
});
test("city database has San Juan", () => {
expect(isCity("San Juan")).toBeTruthy();
});
한번만 setup 할 경우
javascript
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test("city database has Vienna", () => {
expect(isCity("Vienna")).toBeTruthy();
});
test("city database has San Juan", () => {
expect(isCity("San Juan")).toBeTruthy();
});
Scoping
해당 블록 안에서만 setup 됩니다.
javascript
beforeAll(() => console.log("1 - beforeAll"));
afterAll(() => console.log("1 - afterAll"));
beforeEach(() => console.log("1 - beforeEach"));
afterEach(() => console.log("1 - afterEach"));
test("", () => console.log("1 - test"));
describe("Scoped / Nested block", () => {
beforeAll(() => console.log("2 - beforeAll"));
afterAll(() => console.log("2 - afterAll"));
beforeEach(() => console.log("2 - beforeEach"));
afterEach(() => console.log("2 - afterEach"));
test("", () => console.log("2 - test"));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
실행순서
javascript
describe("describe outer", () => {
console.log("describe outer-a");
describe("describe inner 1", () => {
console.log("describe inner 1");
test("test 1", () => console.log("test 1"));
});
console.log("describe outer-b");
test("test 2", () => console.log("test 2"));
describe("describe inner 2", () => {
console.log("describe inner 2");
test("test 3", () => console.log("test 3"));
});
console.log("describe outer-c");
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
javascript
beforeEach(() => console.log("connection setup"));
beforeEach(() => console.log("database setup"));
afterEach(() => console.log("database teardown"));
afterEach(() => console.log("connection teardown"));
test("test 1", () => console.log("test 1"));
describe("extra", () => {
beforeEach(() => console.log("extra database setup"));
afterEach(() => console.log("extra database teardown"));
test("test 2", () => console.log("test 2"));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
테스트가 실패할 경우
테스를 only run 해봅니다.
만약 only run을 해서 실패하지 않는다면 무언가가 테스트를 방해할 수도 있습니다.beforeEach
를 정리하거나 공유되는 state가 확실하지 않을 경우 beforeEach
에서 log
를 확인해볼 수 있습니다.
javascript
test.only("this will be the only test that runs", () => {
expect(true).toBe(false);
});
test("this test will not run", () => {
expect("A").toBe("A");
});