繁体   English   中英

使用 Jest 在 function 内部模拟 class

[英]Mock class inside function using Jest

我正在测试一个 controller,它调用了一个 class,其工作方式类似于 Model。

const getAllProducts = (req, res) => {
    const products = new ProductModel().getAll();

    res.status(200)
    res.send(products)
}
class ProductModel {
    constructor(name, brand) {
        this.id = null;
        this.name = name;
        this.brand = brand;
    }

    getAll() {
        const rawData = fs.readFileSync('./products.json');
        const products = JSON.parse(rawData);

        return products;
    }
}

问题是,我想通过 mocking 测试 controller model 所以它不需要被调用(或者我应该只模拟fs部分,不确定)。

我在函数内部看到了很多与 mocking 函数相关的东西(使用spyOnjest.mock ),但与 class 无关。

通常,您需要模拟/存根对正在测试的方法的直接依赖。 对于您的情况, getAllProducts function 测试不足,因此您需要模拟ProductModel class 的getAll方法。

例如

controller.js

import { ProductModel } from './productModel';

export const getAllProducts = (req, res) => {
  const products = new ProductModel('github', 'reddit').getAll();

  res.status(200);
  res.send(products);
};

productModel.js

export class ProductModel {
  constructor(name, brand) {
    this.id = null;
    this.name = name;
    this.brand = brand;
  }

  getAll() {
    const rawData = fs.readFileSync('./products.json');
    const products = JSON.parse(rawData);

    return products;
  }
}

controller.test.js

import { getAllProducts } from './controller';
import { ProductModel } from './productModel';

describe('61966593', () => {
  it('should pass', () => {
    const mData = { data: [1, 2, 3] };
    const getAllSpy = jest.spyOn(ProductModel.prototype, 'getAll').mockReturnValueOnce(mData);
    const mReq = {};
    const mRes = { status: jest.fn().mockReturnThis(), send: jest.fn() };
    getAllProducts(mReq, mRes);
    expect(getAllSpy).toBeCalledTimes(1);
    expect(mRes.status).toBeCalledWith(200);
    expect(mRes.send).toBeCalledWith({ data: [1, 2, 3] });
    getAllSpy.mockRestore();
  });
});

单元测试的结果:

 PASS  stackoverflow/61966593/controller.test.js (9.078s)
  61966593
    ✓ should pass (4ms)

-----------------|---------|----------|---------|---------|-------------------
File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------------|---------|----------|---------|---------|-------------------
All files        |      80 |      100 |      75 |   78.57 |                   
 controller.js   |     100 |      100 |     100 |     100 |                   
 productModel.js |      70 |      100 |   66.67 |   66.67 | 9-12              
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.273s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM