Ben*_*n R 9 unit-testing asynchronous mocking node.js jestjs
我刚开始使用 Jest 进行单元测试。我如何模拟这个简单的http请求方法“getData”?这是课程:
const got = require("got")
class Checker {
constructor() {
this.url
this.logData = this.logData.bind(this);
this.getData = this.getData.bind(this);
}
async getData(url) {
const response = await got(url);
const data = await response.body;
return data;
}
async logData(first, second, threshold) {
let data = await this.getData(this.url)
console.log("received " + data.body);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试模拟“getData”,以便我可以为“logData”编写单元测试。我需要模拟整个“got”模块吗?谢谢。
如果您更改调用got,got.get您应该能够进行如下工作测试:
const got = require('got');
const Checker = require('../index.js');
describe("some test", () => {
beforeEach(() => {
jest.spyOn(got, 'get').mockResolvedValue({ response: { body: { somekey: "somevalue" } } } );
});
it("works", async () => {
new Checker().getData();
expect(got.get).toBeCalledTimes(1);
})
})
Run Code Online (Sandbox Code Playgroud)
小智 3
一种方法是使用依赖注入。您可以在类构造函数中“请求”并将其分配给私有变量,而不是直接调用“got”。然后,在单元测试中,传递一个模拟版本,它将返回您想要的内容。
const got = require("got");
class Checker {
constructor(gotService) {
this.got = gotService;
this.logData = this.logData.bind(this);
this.getData = this.getData.bind(this);
}
async getData(url) {
const response = await this.got(url);
const data = await response.body;
return data;
}
async logData(first, second, threshold) {
let data = await this.getData(this.url)
console.log("received " + data.body);
}
}
//real code
const real = new Checker(got);
//unit testable code
const fakeGot = () => Promise.resolve(mockedData);
const fake = new Checker(fakeGot);
Run Code Online (Sandbox Code Playgroud)
这是我们正在做的事情: