javascript – JestJS:如何获得模拟函数的不同promise结果并测试抛出的错误?

前端之家收集整理的这篇文章主要介绍了javascript – JestJS:如何获得模拟函数的不同promise结果并测试抛出的错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要测试一个函数(example()),它使用另一个函数(validateDataset).因为我只想测试example()函数,所以我模拟了validateDataset().

当然,每个测试都需要模拟函数的不同结果.但是如何为模拟函数设置不同的promise结果?在我下面显示的尝试中,模拟函数始终返回相同的值.

所以在这个例子中,我无法测试抛出的错误.

functions.js

  1. import { validateDataset } from './helper/validation'
  2.  
  3. export async function example (id) {
  4. const { docElement } = await validateDataset(id)
  5. if (!docElement) throw Error('Missing content')
  6. return docElement
  7. }

functions.test.js

  1. import { example } from './functions'
  2.  
  3. jest.mock('./helper/validation',() => ({
  4. validateDataset: jest.fn(() => Promise.resolve({
  5. docMain: {},docElement: {
  6. data: 'result'
  7. }
  8. }))
  9. }))
  10.  
  11. describe('example()',() => {
  12. test('should return object',async () => {
  13. const result = await example('123')
  14. expect(result.data).toBe('result')
  15. })
  16. test('should throw error',async () => {
  17. const result = await example('123')
  18. // How to get different result (`null`) in this test
  19. // How to test for the thrown error?
  20. })
  21. })

解决方法

Jest模拟的好处在于,你可以模拟整个模块,并且通过要求它的默认或命名导出,你仍然可以得到一个模拟,你可以实现和重新实现,无论你喜欢什么.

我发布了一个测试的示例实现,期望validateDataset调用失败.为简洁起见,我还留了一些评论.

  1. import { example } from './example';
  2. import { validateDataset } from './helper/validation';
  3.  
  4. // Declare export of './helper/validation' as a Mock Function.
  5. // It marks all named exports inside as Mock Functions too.
  6. jest.mock('./helper/validation');
  7.  
  8. test('example() should return object',async () => {
  9. // Because `validateDataset` is already mocked,we can provide
  10. // an implementation. For this test we'd like it to be original one.
  11. validateDataset.mockImplementation(() => {
  12. // `jest.requireActual` calls unmocked module
  13. return jest.requireActual('./helper/validation').validateDataset();
  14. });
  15. const result = await example('123');
  16. expect(result.data).toBe('result');
  17. });
  18.  
  19. test('example() should throw error',async () => {
  20. // Worth to make sure our async assertions are actually made
  21. expect.assertions(1);
  22. // We can adjust the implementation of `validateDataset` however we like,// because it's a Mock Function. So we return a null `docElement`
  23. validateDataset.mockImplementation(() => ({ docElement: null }));
  24. try {
  25. await example('123');
  26. } catch (error) {
  27. expect(error.message).toEqual('Missing content');
  28. }
  29. });

希望能把事情搞清楚.

猜你在找的JavaScript相关文章