用打字稿嘲笑+超级测试

时间:2020-09-28 08:14:31

标签: typescript jestjs supertest

我正在用打字稿开玩笑地编写一个模拟测试用例,并尝试用supertest模拟API调用,但是由于我在登录功能上使用Axios甚至试图模拟Axios,因此无法获得模拟响应作为回报。打电话但没有运气。

这是我的代码:

auth.controller.ts

import { AxiosService } from "helpers";

export class AuthController {
    constructor() {
       ...
      // Some logic is written here
      this.init()
    }

    public init() {
       // prepared an route for login
       router.post('/api/auth/login', this.login);
    }
  
    login = async function (req: Request, res: Response): Promise<void> {
        // Preparing config for axios call with some logic
        ...

        // created a service for Axios call to some third party.
        AxiosService.call(req, res, config, "login");
    }
  }
    
    

auth.test.ts

import { AuthController } from "../../modules/auth/auth.controller";
jest.mock("../../modules/auth/auth.controller");

beforeAll(async () => {
  const auth = new AuthController();
  mockLogin = jest.spyOn(auth, "login");
});

afterAll(async () => {
  server.stop();
});

test("should give login response", async () => {
    mockLogin.mockImplementation(() => {
      return Promise.resolve({ Success: true, body: "Login" });
    });

      const response = await request(server.app)
        .post("/api/auth/login")
        .send(requestBody)
        .expect(200);

      response.body // Getting the server response instead of mocked one
})
    
    

也尝试过此代码,但是那边没有运气:

jest.mock('../../modules/auth/auth.controller', () => {
  return { 
    AuthController: jest.fn().mockImplementation(() => {
          return {
              login: jest.fn()
          }   
      })
  }
})
            
    

这是我的 AxiosService 类:

export class AxiosService {

  public static async call(...):Promise<void> { 
    try { 
       const { data } = await axios(...);

       res.status(200).json(data);
    } catch(err) {
       res.status(400).send(err);
     }
  
  }

}

尝试用以下行模拟 AxiosService 调用方法:

jest.mock('../../helpers/AxiosService', () => {
  return jest.fn().mockImplementation(() => {
    return { call: () => { return {success:true, data:'mock'}} }
  })
})

但是,在模拟Axios调用后,我得到未在jest.setTimeout指定的10000(我给定的)ms超时内调用异步回调

任何人都可以帮上忙,这对我非常有用,因为我是模拟概念的新手,所以也许我在这里错过了一些东西。

预先感谢

1 个答案:

答案 0 :(得分:1)

一种适当的测试策略,除了测试的每个单元都需要模拟。

发生超时是因为Supertest等待服务器响应,并且在模拟AxiosService的情况下没有超时,因此需要像这样模拟:

...
return { call: (req, res) => { res.status(200).json({success:true, data:'mock'}); }

在这种情况下,测试可以使用模拟的服务类模拟控制器类,或与模拟的Axios一起测试它们。由于AuthController并不会做很多事情(AuthController和AxiosService是对简单Express处理程序的抽象),因此可以是:

jest.mock('axios', () => jest.fn()) // at top level
...
axios.mockResolvedValue({ data: ... });
const response = await request(server.app)