jestjs - 开 Jest 异步测试 - expect.assertion 似乎是全局性的

标签 jestjs

我有以下单元测试:

var { Mockgoose } = require("mockgoose");
var mongoose = require("mongoose");
var Transaction = require("./transaction");

var mockgoose = new Mockgoose(mongoose);

describe("transaction", function() {
  afterEach(function() {
    return mockgoose.helper.reset();
  });

  afterAll(function() {
    const { connections } = mongoose;
    const { childProcess } = mockgoose.mongodHelper.mongoBin;
    // kill mongod
    childProcess.kill();
    // close all connections
    for (const con of connections) {
      return con.close();
    }
    return mongoose.disconnect();
  });

  test("category is required", function() {
    expect.assertions(1);
    return mockgoose.prepareStorage().then(function() {
      mongoose.connect("mongodb://foobar/baz");
      return mongoose.connection.on("connected", function() {
        var mockTransaction = new Transaction({
          amount: 25,
          comment: "Gas money, Petrol.",
          tags: ["Gas", "Car", "Transport"],
          currency: "EUR"
        });
        return mockTransaction.save(function(err, savedTransaction) {
          expect(err.errors.category.properties.message).toBe(
            "Category is required."
          );
        });
      });
    });
  });

  test("category should match one of the predefined categories", function() {
    expect.assertions(1);
    return mockgoose.prepareStorage().then(function() {
      mongoose.connect("mongodb://foobar/baz");
      return mongoose.connection.on("connected", function() {
        var mockTransaction = new Transaction({
          category: "dsawdsfawfsaf",
          amount: 25,
          comment: "Gas money, Petrol.",
          tags: ["Gas", "Car", "Transport"],
          currency: "EUR"
        });
        return mockTransaction.save(function(err, savedTransaction) {
          expect(err.errors.category.properties.message).toBe(
            "{VALUE} is not a valid category."
          );
        });
      });
    });
  });
});

现在,如果我只运行其中一个测试,一切都会通过,但是当我运行这两个测试时,我会收到以下错误:

● transaction › category should match one of the predefined categories

expect.assertions(1)

Expected one assertion to be called but received two assertion calls.

  43 | 
  44 |   test("category should match one of the predefined categories", function() {
> 45 |     expect.assertions(1);
     |            ^
  46 |     return mockgoose.prepareStorage().then(function() {
  47 |       mongoose.connect("mongodb://foobar/baz");
  48 |       return mongoose.connection.on("connected", function() {


每个测试不应该有自己的断言和自己的期望吗?

最佳答案

我在我的代码中发现,当我混合使用“异步”和“同步”测试来测试异步功能时,就会出现问题。

我使用导致问题的 jest expect().resolves/rejects API 以“同步方式”测试了异步函数。不得不以 async-await 风格重写测试。那解决了这个问题。

describe('asyncSum()', () => {
  test('"broken" sync test', () => {
    expect(asyncSum(2, 2)).resolves.toEqual(4); // This line causes the issue incorrect assertion count
  })

  test('async test resolves example', async () => {
    expect.assertions(1);

    const sum = await asyncSum(2, 2);
    expect(sum).toEqual(4);
  })

  test('async test reject example', async () => {
    expect.assertions(1);

    let error;
    try {
      await asyncSum(2);
    } catch (err) {
      error = err;
    }

    expect(error.message).toEqual('Missing 2nd parameter')
  }
})

关于jestjs - 开 Jest 异步测试 - expect.assertion 似乎是全局性的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51105594/

相关文章:

javascript - 如何在 Jest/Enzyme 上测试子组件

javascript - Jest 的匹配器错误 : received value must be a function

react-redux - Jest + enzyme : test Redux-form

javascript - Next.js 和 Jest : SyntaxError: Cannot use import statement outside a module

node.js - 为什么多次调用 jest mockResolvedValueOnce 返回相同的值?

reactjs - React Native - Jest : Broken since update to 0. 56. 如何修复它?

unit-testing - 在单元测试中触发 vue-select 下拉项选择

reactjs - 在 React 中测试嵌套组件

typescript - TS-Jest 无法解析 tsconfig 路径

reactjs - 使用jestjs进行单元测试时如何获取组件的props