Jest 中的 'it' 和 'test' 有什么区别?

687

我在我的测试组中有两个测试。其中一个测试使用it,另一个使用test。它们似乎非常相似。它们之间有什么区别?

describe('updateAll', () => {
  it('no force', () => {
    return updateAll(TableName, ["fileName"], {compandId: "test"})
        .then(updatedItems => {
          let undefinedCount = 0;
          for (let item of updatedItems) {
            undefinedCount += item === undefined ? 1 : 0;
          }
          // console.log("result", result);
          expect(undefinedCount).toBe(updatedItems.length);
        })
  });

  test('force update', () => {
    return updateAll(TableName, ["fileName"], {compandId: "test"}, true)
        .then(updatedItems => {
          let undefinedCount = 0;
          for (let item of updatedItems) {
            undefinedCount += item === undefined ? 1 : 0;
          }
          // console.log("result", result);
          expect(undefinedCount).toBe(0);
        })
  });
});

更新 - 2022年11月:

根据Jest官方API,似乎testit可以互换使用。正如@gwildu在这里所描述的那样,为了更好的可读性,您应该选择其中之一。


它可能只是为了熟悉性和从其他框架迁移而存在。 - Andrew Li
69
没有任何区别。文档明确指出,“test”是“it”的别名。 - Claies
它们的逻辑相似,但在阅读方面它们的语义不同。 - Suleman Elahi
10个回答

891

Jest 文档 中提到 ittest 的别名。从功能的角度来看,它们完全相同。它们都用于使您的测试内容成为可读的英语句子。


250

它们做着相同的事情,但它们的名称不同,因此它们与测试名称的交互也不同。

测试

您所写的内容:

describe('yourModule', () => {
  test('if it does this thing', () => {});
  test('if it does the other thing', () => {});
});

如果某些事情失败了,您将得到什么:

yourModule > if it does this thing

it

What you write:

describe('yourModule', () => {
  it('should do this thing', () => {});
  it('should do the other thing', () => {});
});

如果某个问题发生了,你会得到什么:

yourModule > should do this thing

所以这与功能无关,而是与可读性有关。

在我看来,当你阅读一个你自己没有编写的失败测试结果时,it确实有一点道理。它有助于更快地理解测试的内容。

一些开发人员也将应该做这件事缩短为做这件事,这样更简洁,并且语义上也符合it的表示方法。


16
有些人更喜欢使用 it('does this thing', () => {}) 而不是 it('should do this thing', () => {}),因为前者更短。 - gwildu
作为替代,test('thing should do x') 可能比 it('Should do X') 更受欢迎,因为 it 经常含糊不清。 - mikemaccana
1
如果你写 test('thing should do x'),那么你没有一个语义上正确的句子。我认为这些符号背后的想法是,你可以像说话一样在句子中读取测试。如果你写 test('Does this thing') 也是一样的。当然你可以这样做,但符号实际上更适合使用 it 符号。 - gwildu
2
test('thing should do x') 字面上是“测试那个东西应该做X” - 因此测试读起来就像说话一样。 test('thing does x') 也可以。 - mikemaccana

46

正如其他答案所澄清的那样,它们做相同的事情。

我认为这两个选项的提供是为了允许使用类似于"RSpec"风格的测试:

const myBeverage = {
  delicious: true,
  sour: false,
};

describe('my beverage', () => {
  it('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  it('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

或者2)像 "xUnit" 风格的测试,例如:

function sum(a, b) {
  return a + b;
}

test('sum adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Documentation:


12

正如 Jest 文档所说,它们是一样的:it 别名

test(name, fn, timeout)

也可以使用别名:it(name, fn, timeout)

describe 只是用于将测试分组:

describe

describe(name, fn)

describe(name, fn) 创建一个块,将几个相关的测试组合在一起。例如,如果你有一个 myBeverage 对象,它应该 delicious 但不是 sour,你可以这样测试:

const myBeverage = {
  delicious: true,
  sour: false,
};

describe('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

这不是必须的 - 你可以直接在顶层编写测试块。但如果您喜欢将测试组织成组,这可能会很方便。


9

你可以使用xit()代替it()来暂时排除一个测试不被执行; 使用it()xit()比使用test()xit()更优雅。

请参阅聚焦和排除测试


4
也有一个叫做“xtest”的东西,所以两者几乎相同。 - yuriy636
xit() 也更短。 - Adrian

4
以下是文件的摘录:链接

test(name, fn, timeout)

别名: it(name, fn, timeout)

在测试文件中,你只需要使用 test 方法来运行测试。例如,假设有一个函数 inchesOfRain() 应该为零。整个测试可以是:......


-5

const request = require('supertest'); const app = require('../app') const {it, describe} = require('@jest/globals'); const { sequelize } = require('../models'); const {hash} = require('../helpers/bcrypt')

beforeAll(async ()=>{ await sequelize.queryInterface.bulkInsert('Customers', [{ username: "nikita", email:"nikita@mail.com", password: hash("nikita"), createdAt: new Date(), updatedAt: new Date() }]) })

afterAll(async ()=>{ await sequelize.queryInterface.bulkDelete('Customers', null, { truncate: true, cascade: true, restartIdentity: true }) })

describe('POST /customers/register', () => { it('应该响应状态码201', async ()=> { let customer = { username: "hello" , email:"hello@mail.com", password:"hello", } let response = await request(app) .post('/customers/register').send(customer) expect(response.status).toBe(201) // console.log(response.body, 'ini ressss') expect(response.body).toEqual({ message: "输入客户数据成功", id: expect.any(Number), email: expect.any(String) }) }); it('应该响应状态码400', async()=>{ let customer = { username: "hello", password:"hello" } let response = await request(app) .post('/customers/register').send(customer) expect(response.status).toBe(400) // console.log(response.body,"<<<"); expect(response.body[0].message).toBe('请输入电子邮件') })


1
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

-5
`const request = require('supertest');`
`const app =  require('../app')`
`const {it, describe} = require('@jest/globals');`
`const { sequelize, Category, User, News , Customer, Bookmark} = require('../models');`
`const {hash} = require('../helpers/bcrypt');`
`const news = require('../models/news');`
`const {queryInterface} = sequelize`


`beforeAll(async()=>{

    let userData = require("../data/user.json")
    userData.forEach(el => {
        el.password = hash(el.password)
        el.createdAt = new Date()
        el.updatedAt = new Date()
    });`

`afterAll(async ()=>{
    await Bookmark.destroy({
        truncate: true,
        cascade: true,
        restartIdentity: true
    })`

`describe('GET /customers/news', () => {
    it("should response with status 200 1", async () => {
        let response = await request(app)
        .get('/customers/news')
        // .set({access_token})
        // console.log(response.body, "<<<<NEWS NIhH");
        expect(response.status).toBe(200)
        expect(response.body).toBeInstanceOf(Array)
    })`

`it("should response with status 200 2", async()=>{
    let response = await request(app)
    .get('/customers/news?filter=1,2')
    expect(response.status).toBe(200)
    expect(response.body).toBeInstanceOf(Array)
})`

你的回答可以通过添加更多支持性信息来改进。请[编辑]以添加更多细节,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心中找到有关撰写良好答案的更多信息。 - Community

-20
Jest没有提到为什么他们有两个版本的完全相同的功能。
我猜,这只是为了遵循惯例。test用于单元测试,it用于集成测试。

-37

它们是同一件事。我使用TypeScript作为编程语言,当我查看来自Jest包源代码/@types/jest/index.d.ts的定义文件时,可以看到以下代码。

显然,有很多不同名称的“test”,您可以使用其中任何一个。

declare var beforeAll: jest.Lifecycle;
declare var beforeEach: jest.Lifecycle;
declare var afterAll: jest.Lifecycle;
declare var afterEach: jest.Lifecycle;
declare var describe: jest.Describe;
declare var fdescribe: jest.Describe;
declare var xdescribe: jest.Describe;
declare var it: jest.It;
declare var fit: jest.It;
declare var xit: jest.It;
declare var test: jest.It;
declare var xtest: jest.It;


40
你展示的代码并没有表明ittest是相同的东西,它只是意味着它们的类型相同。尽管它们的类型相同,我认为beforeAllafterAll并不是相同的东西。 - realUser404
6
"xit和xtest"跳过测试,而"it、fit、test"是执行测试。谢谢你的提问。 - Aakash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接