我如何单元测试的JavaScript中承诺的“然后”结果呢?

问题描述 投票:1回答:2

我使用的打字稿写了一个非常简单的服务,利用AWS SDK。我的玩笑单元测试都通过,但说的覆盖报告,该行“回归result.Items”不是盖的。谁能告诉这是为什么?它是在开玩笑的错误吗?

// service file

/**
 * Gets an array of documents.
 */
function list(tableName) {
  const params = {
    TableName: tableName,
  };
  return docClient
    .scan(params)
    .promise()
    .then((result) => {
      return result.Items;
    });
}

// test file

const stubAwsRequestWithFakeArrayReturn = () => {
  return {
    promise: () => {
      return { then: () => ({ Items: 'fake-value' }) };
    },
  };
};

it(`should call docClient.scan() at least once`, () => {
  const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
  aws.docClient.scan = mockAwsCall;
  db.list('fake-table');
  expect(mockAwsCall).toBeCalledTimes(1);
});

it(`should call docClient.scan() with the proper params`, () => {
  const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
  aws.docClient.scan = mockAwsCall;
  db.list('fake-table');
  expect(mockAwsCall).toBeCalledWith({
    TableName: 'fake-table',
  });
});

it('should return result.Items out of result', async () => {
  const mockAwsCall = jest
    .fn()
    .mockImplementation(stubAwsRequestWithFakeArrayReturn);
  aws.docClient.get = mockAwsCall;
  const returnValue = await db.get('fake-table', 'fake-id');
  expect(returnValue).toEqual({ Items: 'fake-value' });
});
javascript typescript unit-testing jestjs
2个回答
3
投票

不包括该生产线是传递给then成功回调。

你的模拟替代then与不接受任何参数,只是返回一个对象的功能。从你的代码的回调传递给测试期间then模拟,但它不调用回调使Jest正确地报告回调不属于你的测试。

不要试图返回一个模仿的对象,看起来像一个Promise,只是从你的模拟返回一个实际的解决Promise

const stubAwsRequestWithFakeArrayReturn = () => ({
  promise: () => Promise.resolve({ Items: 'fake-value' })
});

......方式then仍然将是实际Promise.prototype.then如预期回调将被调用。


你也应该await返回Promise,以确保测试完成之前的回调被称为:

it(`should call docClient.scan() at least once`, async () => {
  const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
  aws.docClient.scan = mockAwsCall;
  await db.list('fake-table');  // await the Promise
  expect(mockAwsCall).toBeCalledTimes(1);
});

it(`should call docClient.scan() with the proper params`, async () => {
  const mockAwsCall = jest.fn().mockImplementation(stubAwsRequest);
  aws.docClient.scan = mockAwsCall;
  await db.list('fake-table');  // await the Promise
  expect(mockAwsCall).toBeCalledWith({
    TableName: 'fake-table',
  });
});

0
投票

图书馆柴-AS-承诺是值得看的。

https://www.chaijs.com/plugins/chai-as-promised/

不用手动布线你的期望,一个承诺的兑现,并拒绝处理。

doSomethingAsync().then(
    function (result) {
        result.should.equal("foo");
        done();
    },
    function (err) {
       done(err);
    }
);

您可以编写代码,表示你真正的意思:

return doSomethingAsync().should.eventually.equal("foo");
© www.soinside.com 2019 - 2024. All rights reserved.